1

I'm new to Java 8 and Streams . I got a PolicyDefinition object, that got to two method : getAlias,getName which both returns a string . Is there an elegant way to create a list with all aliases and names of policy definitions using Stream (created from collection of PolicyDefinition) in one statement ?

with two statements its not a problem :

List<String> policyNames = 
              policyDefinitions.stream()
                               .map(definition -> definition.getName())
                               .collect(Collectors.toList());

List<String> policyAlias = 
              policyDefinitions.stream()
                               .map(definition -> definition.getAlias())
                               .collect(Collectors.toList());

But Is it possible in one ?

Thanks a lot for the help

2 Answers 2

4

flatMap it!

List<String> policyNames = policyDefinitions.stream()
    .flatMap(definition -> Stream.of(definition.getName(), definition.getAlias()))
    .collect(Collectors.toList());

As mentioned in the comments - for tidyness, create a method in Definition

public Stream<String> allNames() {
    return Stream.of(getName(), getAlias())
}

Then

List<String> policyNames = policyDefinitions.stream()
    .flatMap(Definition::allNames)
    .collect(Collectors.toList());

OP comments "I forgot to mention that getAlias might be null, what do you do than[sic]"

In that case, use Optional:

public Stream<String> allNames() {
    return Stream.concat(Stream.of(getName()), Optional.ofNullable(getAlias()).stream())
}
Sign up to request clarification or add additional context in comments.

4 Comments

I forgot to mention that getAlias might return null, what do you do than ?
Note, that optional only had a stream method as of JDK9, an alternative for JDK8 could be to create your own method that does such thing or filter the nulls out like List<String> policyNames = policyDefinitions.stream() .flatMap(Definition::allNames).filter(Objects::nonNull) .collect(Collectors.toList());
@Aominè Good point Optional.map(Stream::of).orElseGet(Stream::empty) was a favourite of mine.
Or simply Stream.of(getName(), getAlias()).filter(Objects::nonNull)
0

Also you can create a Map with Alias as a Key and Name as a Value using groupingBuy operator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.