Remove duplicates from ArrayLists

后端 未结 14 2175
孤街浪徒
孤街浪徒 2020-11-27 04:12

I have an ArrayList of custom objects. I want to remove duplicate entries.

The objects have three fields: title, subtitle, and id. If a su

相关标签:
14条回答
  • 2020-11-27 04:37

    If I understand correctly you have an ArrayList<Custom>, let's call it list. Your Custom class has a subtitle field, let's say with a getSubtitle() method that returns String. You want to keep only the first unique subtitle and remove any remaining duplicates. Here's how you can do that:

    Set<String> subtitles = new HashSet<String>();
    for (Iterator<Custom> it = list.iterator(); it.hasNext(); ) {
        if (!subtitles.add(it.next().getSubtitle())) {
            it.remove();
        }
    }
    
    0 讨论(0)
  • In Java 8, you can also do something like this:

    yourList.stream().collect(
         Collectors.toMap(
             obj -> obj.getSubtitle(),
             Function.identity(), 
             (o1,o2) -> o1))
        .values();
    

    The trick is to collect stream to map and provide key collision resolver lambda ((o1,o2) -> o1) which always returns its first parameter. The result is a Collection, not a List but you can easily convert it to a List:

    new ArrayList(resultCollection);
    
    0 讨论(0)
  • 2020-11-27 04:39

    Use Collections.sort() to sort and use a simple for cycle to catch doubles, e.g.:

    Collections.sort(myList);
    A previous = null;
    for (A elem: myList) {
        if (elem.compareTo(previous) == 0) continue;
        previous = elem;
    
        [... process unique element ...]
    }
    

    This presumes that you'll implement Comparable in your type A.

    0 讨论(0)
  • 2020-11-27 04:39
    private static List<Integer> removeDuplicates(List<Integer> list) {
        ArrayList<Integer> uniqueList = new ArrayList<Integer>();
        for (Integer i : list) {
            if (!inArray(i, uniqueList)) {
                uniqueList.add(i);
            }
        }
    
        return uniqueList;
    }
    
    private static boolean inArray(Integer i, List<Integer> list) {
        for (Integer integer : list) {
            if (integer == i) {
                return true;
            }
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2020-11-27 04:42

    Another method using Java 8 streams you can also do pretty cool:

    List<Customer> CustomerLists;
    List<Customer> unique = CustomerLists.stream().collect(collectingAndThen(
            toCollection(() -> new TreeSet<>(comparingLong(Customer::getId))),
            ArrayList::new));
    
    0 讨论(0)
  • 2020-11-27 04:46

    Update for Java8:

    Using Java8 streams you can also do pretty trivally.

    ArrayList<String> deduped;
    deduped = yourArrayList.stream()
                 .distinct()
                 .collect(Collectors.toCollection(ArrayList::new));
    

    This also has the advantage over going ArrayListSetArrayList of maintaining ordering.

    0 讨论(0)
提交回复
热议问题