Java List Comparison: Compare Objects in Lists

In Java, there are several ways to compare the values of objects in two lists.

  1. You can compare the objects in two Lists for equality using the equals() method. One way is to iterate through the objects in each List and compare them individually, or you can directly use the List’s equals() method for comparison.
List<Object> list1 = new ArrayList<>();
List<Object> list2 = new ArrayList<>();

// 添加对象到list1和list2中

if(list1.equals(list2)){
    System.out.println("两个List中的对象值相等");
} else {
    System.out.println("两个List中的对象值不相等");
}
  1. The containsAll() method in Collections is used to compare the values of objects in two lists to see if they are equal. This method compares whether the elements in two lists are the same, regardless of the order of the elements.
List<Object> list1 = new ArrayList<>();
List<Object> list2 = new ArrayList<>();

// 添加对象到list1和list2中

if(list1.size() == list2.size() && list1.containsAll(list2)){
    System.out.println("两个List中的对象值相等");
} else {
    System.out.println("两个List中的对象值不相等");
}
  1. Use the Stream API for comparison. You can convert the objects in two lists into streams, and then use the equals() method of the Stream to compare if the two streams are equal.
List<Object> list1 = new ArrayList<>();
List<Object> list2 = new ArrayList<>();

// 添加对象到list1和list2中

boolean isEqual = list1.stream()
                        .allMatch(obj -> list2.contains(obj)) 
                        && list2.stream()
                                .allMatch(obj -> list1.contains(obj));

if(isEqual){
    System.out.println("两个List中的对象值相等");
} else {
    System.out.println("两个List中的对象值不相等");
}
bannerAds