Reputation: 971
I have a requirement to fetch the sublist from a given super list as explained below.
Let's say I have a super list of "Person" objects as follows:
List<Person> personsList = new ArrayList<>();
personsList.add(new Person("John", 28));
personsList.add(new Person("Paul", 29));
personsList.add(new Person("Adam", 30));
personsList.add(new Person("Peter", 31));
personsList.add(new Person("Kate", 32));
personsList.add(new Person("John", 67));
personsList.add(new Person("Paul", 68));
personsList.add(new Person("Adam", 69));
Let the Person class be defined as follows:
class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + ": " + age;
}
}
By using Java Streams API, how do I fetch a sub list with the entries like below (note that the repeated instances of objects with same name have to be fetched):
John : 28
John : 67
Paul : 29
Paul : 68
Adam : 30
Adam : 69
Can someone please help me in achieving this by using Java 8 Streams API?
P.S : I would not pre handedly know what values are there as names for those objects.
Upvotes: 2
Views: 157
Reputation: 21975
The following operation will give you your awaited result. You first group by the name all your persons, from the resulting list, you exclude all the ones with a size less than 2 and flatMap everything, sort it and print everything
personsList.stream()
.collect(Collectors.groupingBy(Person::getName))
.values()
.stream()
.filter(list -> list.size() > 1)
.flatMap(List::stream)
.forEach(System.out::println);
Output
Adam: 30
Adam: 69
John: 28
John: 67
Paul: 29
Paul: 68
Upvotes: 6