Java 8 Stream find objects in list that match some properties

Viewed 1910

Let's say I have the next list

List<MyData> list = new ArrayList<>();
list.add(new MyData("id1", "name1", "secondName1", "phone1", "address1");
list.add(new MyData("id2", "name2", "secondName1", "phone2", "address2");
list.add(new MyData("id3", "name3", "secondName3", "phone1", "address1");
list.add(new MyData("id4", "name4", "secondName4", "phone4", "address4");

Using Java8 streams, I want to find in my list which items have the same phone and same address.

I've seen in this forum a lot of solutions to reduce lists filtering only by one property, but I need to match two or more properties.

1 Answers

You could do:

 list.stream()
            .collect(Collectors.collectingAndThen(
                    Collectors.groupingBy(
                            x -> Arrays.asList(x.getPhone(), x.getAddress()),
                            HashMap::new,
                            Collectors.toList()),
                    map -> {
                        map.values().removeIf(x -> x.size() == 1);
                        return map.values();
                    }));
Related