Skip to content
Advertisement

Java 8 List from String and List of String

I want to generate a list of strings, comprising id and external ids, from a list of Bean.

public class User {
    private String id;
    private List<String> externalIds;
}

I got it using the below code, but here I need to do the stream twice.

List<User> references = new ArrayList();
Stream.concat(references.stream().map(User::getId),
references.stream().map(User::getExternalIds).flatMap(Collection::stream))
            .collect(Collectors.toList());

Is there any better way to rewrite this code?

Advertisement

Answer

Use Stream.concat inside the flatMap operation:

references.stream()
        .flatMap(user -> Stream.concat(
            Stream.of(user.getId()),
            user.getExternalIds().stream()
        ))
        .collect(Collectors.toList())
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement