对比list对象

52 阅读2分钟

此实现通过首先创建一个映射来存储第一个列表中每个 bean 的频率来工作。然后,我们遍历第二个列表中的每个元素,检查 bean 是否在映射中。如果 bean 不在映射中,则列表不相等。如果 bean 在地图中,我们将减少它的频率。在遍历第二个列表中的所有元素后,如果频率映射为空,则列表相等。

当我们发现两个不相等的 bean 时,我们比较 bean 的每个字段并打印一条消息,指示哪个字段不相等。您可以修改此实现以比较其他字段或在必要时使用不同的比较方法。

请注意,此实现假定 Bean 类已正确实现 equals 和 hashCode 方法。如果 Bean 类没有正确实现这些方法,这个实现可能无法按预期工作。

public static boolean compareLists(List<Bean> list1, List<Bean> list2) {
    // Check if the two lists have the same size
    if (list1.size() != list2.size()) {
        return false;
    }

    // Create a map to store the frequency of each bean in the first list
    Map<Bean, Integer> frequencyMap = new HashMap<>();
    for (Bean bean : list1) {
        frequencyMap.put(bean, frequencyMap.getOrDefault(bean, 0) + 1);
    }

    // Iterate over each element of the second list and compare their properties
    for (int i = 0; i < list2.size(); i++) {
        Bean bean2 = list2.get(i);
        Integer frequency = frequencyMap.get(bean2);

        // If the bean is not in the first list, the lists are not equal
        if (frequency == null) {
            return false;
        }

        // If the bean is in the first list, decrement its frequency
        if (frequency == 1) {
            frequencyMap.remove(bean2);
        } else {
            frequencyMap.put(bean2, frequency - 1);
        }

        // Compare the properties of the beans
        Bean bean1 = null;
        for (Bean b : list1) {
            if (b.equals(bean2)) {
                bean1 = b;
                break;
            }
        }

        if (!bean1.equals(bean2)) {
            // If the beans are not equal, compare each field
            if (!bean1.getProperty1().equals(bean2.getProperty1())) {
                System.out.println("Property 1 of bean " + i + " is not equal");
            }
            if (bean1.getProperty2() != bean2.getProperty2()) {
                System.out.println("Property 2 of bean " + i + " is not equal");
            }
            // Add more comparisons for other fields if needed

            return false;
        }
    }

    // If all elements are equal, the lists are equal
    return frequencyMap.isEmpty();
}

Bean类如下 : bean需要重写equals方法。

public class Bean {
    private String property1;
    private int property2;

    // Constructor, getters and setters

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Bean other = (Bean) obj;
        if (!Objects.equals(this.property1, other.property1)) {
            return false;
        }
        if (this.property2 != other.property2) {
            return false;
        }
        return true;
    }
}