Java 8 Distinct by property

后端 未结 29 2292
傲寒
傲寒 2020-11-21 22:35

In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?

For example I have a list of

29条回答
  •  不要未来只要你来
    2020-11-21 23:10

    Building on @josketres's answer, I created a generic utility method:

    You could make this more Java 8-friendly by creating a Collector.

    public static  Set removeDuplicates(Collection input, Comparator comparer) {
        return input.stream()
                .collect(toCollection(() -> new TreeSet<>(comparer)));
    }
    
    
    @Test
    public void removeDuplicatesWithDuplicates() {
        ArrayList input = new ArrayList<>();
        Collections.addAll(input, new C(7), new C(42), new C(42));
        Collection result = removeDuplicates(input, (c1, c2) -> Integer.compare(c1.value, c2.value));
        assertEquals(2, result.size());
        assertTrue(result.stream().anyMatch(c -> c.value == 7));
        assertTrue(result.stream().anyMatch(c -> c.value == 42));
    }
    
    @Test
    public void removeDuplicatesWithoutDuplicates() {
        ArrayList input = new ArrayList<>();
        Collections.addAll(input, new C(1), new C(2), new C(3));
        Collection result = removeDuplicates(input, (t1, t2) -> Integer.compare(t1.value, t2.value));
        assertEquals(3, result.size());
        assertTrue(result.stream().anyMatch(c -> c.value == 1));
        assertTrue(result.stream().anyMatch(c -> c.value == 2));
        assertTrue(result.stream().anyMatch(c -> c.value == 3));
    }
    
    private class C {
        public final int value;
    
        private C(int value) {
            this.value = value;
        }
    }
    

提交回复
热议问题