There are 2 sheets:

ArrayList<String> list = new ArrayList<String>(); list.add("a"); list.add("a"); list.add("b"); ArrayList<String> list001 = new ArrayList<String>(); list001.add("a"); list001.add("b"); list001.add("a"); 

It is necessary to find out whether the values ​​of their cells are equal without regard to their order and sequence, that is, these can be considered equal = true; Bearing in mind that there may be many such elements ...

You can use any features except framvorkov. Maybe there is a short way, for sure the san has provided such a thing. Maybe someone knows?

  • one
    containsAll(Collection<?> c) tried? - MrFylypenko
  • one
    @MrFylypenko if the second list, for example, removes one of the "a" (for example, the last), then containsAll will show true anyway - Alexey Shimansky
  • I did not know about this method thanks! - Pavel
  • one
    @ Alexey Shimansky is true, it will show true, but he will not sort arrays and hopefully he will solve the tasks. I like your version too. - MrFylypenko
  • Alexey Shimansky didn’t really notice ... - Pavel

4 answers 4

As an option, sort the collections and compare them:

 Collections.sort(list); Collections.sort(list001); System.out.println(list.equals(list001)); 

should help

    If the lists cannot be sorted, you can count the number of entries of each element in the list and compare:

     List<String> first = Arrays.asList( "a", "b", "a" ); List<String> second = Arrays.asList( "a", "a", "b" ); // используется import static java.util.stream.Collectors.*; // иначе это еще страшнее выглядит first.stream().collect( groupingBy( k -> k, counting()) ) .equals( second.stream().collect( groupingBy( k -> k, counting()) ) ) 

      Maybe I did not fully understand the essence of the question, but if there is a need to compare each element separately, then you can try this method:

       public static void compareTwoLists(ArrayList list, ArrayList list2){ for(int i = 0; i < list.size(); i++){ for(int j = 0; j < list.size(); j++){ if(list.get(i).equals(list2.get(j)) == true){ System.out.println("Элемент " + i + " первого массива равен элементу " + j + " второго массива."); }else{ System.out.println("Элемент " + i + " первого массива не равен элементу " + j + " второго массива."); } } } } 

        To compare the two collections, you can use HashSet.

        In my example, it was necessary to compare two lists of objects, I did it by their unique ID (instead of Integer, there could be a String, as in your example).

          Set<Integer> objectsIds = new HashSet<>(); for (Object object : objectList1) { objectsIds.add(object.getId()); } for (Object object : objectList2) { if (objectsIds.contains(object.getId())) { objectsIds.remove(object.getId()); } else { objectsIds.add(object.getId()); } } 

        At the output we get a set that is empty if the collections are the same, otherwise we get the difference.

        Check:

         objectsIds.isEmpty();