I have a List of Objects where each object that returns List.
How can I use Java 8 streams to get only one List?
Contact class has the following method;
public List getSharedFriendsIds() {
return sharedFriendsIds;
}
And I have
List contactsList;
What I was trying was
List sharedContacts = contactsList.stream()
.map(Contact::getSharedFriendsIds)
.sequential()
.collect(Collectors.toList());
But above line is not returning List but rather List> which is not what I want.
解决方案
You should use .flatMap() to create a single list from the sharedFriendsIds list that is contained in each Contact object from the main list contactsList. Please check the following;
List sharedContacts = contactsList.stream()
.filter(contacts -> contacts.getSharedFriendsIds() != null)
.flatMap(contacts -> contacts.getSharedFriendsIds().stream())
.sorted().collect(Collectors.toList());
The .filter() call is for the case when there is any contact with sharedFriendsIds == null in the list, since that would cause NPE in the next line, we ought to filter those out. There are other ways to achieve that like;
List sharedContacts = contactsList.stream()
.flatMap(contacts -> Optional.ofNullable(contacts.getSharedFriendsIds())
.map(List::stream).orElseGet(Stream::empty))
.sorted().collect(Collectors.toList());
Where the filtering of null sharedFriendsIds are done in such a way that they are absorbed into the flatMap logic as empty streams.
Also you used .sequential for the sort logic, I guess, you should've used .sorted method, since sequential is for triggering non-parallel usage, which is already the default configuration of a default Stream.