Search code examples
javajava-8java-stream

Find objects in list that match some properties using a Java 8 stream


Let's say I have the following 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 Java 8 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.


Solution

  • 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();
                        }));