我有一个输入:
Apple: 0 1
Apple: 4 5
Pear: 0 10
Pear: 11 13
Apple: 5 10
Apple: 2 4
我正在寻找行,其中水果是相同的,第一个值等于另一行的第二个谷。所以我正在寻找像Apple: 4 5
Apple: 2 4
这样的行,我还需要Apple: 4 5
Apple: 5 10
另一方面,我不想搜索整个数据。我的意思是我不想在Apple
中搜索Pears
。
我应该使用HashMap吗?还是HashSet?或其他什么?
感谢您的回复。
答案 0 :(得分:0)
尝试一下......它使用HashMap
List
s
public static void main(String[] args) {
List<String> inputs = new ArrayList<>();
inputs.add("Apple: 0 1");
inputs.add("Apple: 4 5");
inputs.add("Pear: 0 10");
inputs.add("Pear: 11 13");
inputs.add("Apple: 5 10");
inputs.add("Apple: 2 4");
Map<String, List<Fruit>> fruits = new HashMap<>();
for (String input : inputs) {
String[] inputPieces = input.split(" ");
String name = inputPieces[0].replace(":", "");
int first = Integer.parseInt(inputPieces[1]);
int second = Integer.parseInt(inputPieces[2]);
if (!fruits.containsKey(name)) {
fruits.put(name, new ArrayList<Fruit>());
}
fruits.get(name).add(new Fruit(name, first, second));
}
for (String key : fruits.keySet()) {
System.out.println(key + ": " + findDuplicates(fruits.get(key)));
}
}
private static List<Fruit> findDuplicates(List<Fruit> fruits) {
List<Fruit> results = new ArrayList<>();
for (int i = 0; i < fruits.size(); i++) {
for (int j = 0; j < fruits.size(); j++) {
if (j == i) {
continue;
}
if ((fruits.get(i).first == fruits.get(j).second) ||
(fruits.get(j).first == fruits.get(i).second)) {
if (!results.contains(fruits.get(i))){
results.add(fruits.get(i));
}
}
}
}
return results;
}
public static class Fruit {
private String name;
private int first;
private int second;
public Fruit(String name, int first, int second) {
this.name = name;
this.first = first;
this.second = second;
}
@Override
public String toString() {
return String.format("%s: %d %d", name, first, second);
}
}
结果: