在输入中查找重复值

Find duplicate values in input

我有这样的输入:

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

另一方面,我不想搜索整个数据。我的意思是我不想在 Pears.

中搜索 Apple

我应该使用HashMap吗?还是哈希集?还是别的?

感谢回复。

试一试...它利用 HashMapLists

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);
    }
}

结果: