Java Stream - Combine Two Streams

Viewed 385

Is there a way I can combine these two streams into one?

Here's the first stream

Map<String, String> rawMapping = tokens.getColumnFamilies().stream()
            .filter(family -> family.getName().equals("first_family"))
            .findAny()
            .map(columns -> columns.getColumns().stream()).get()
            .collect(Collectors.toMap(
                Column::getPrefix,
                Column::getValue
            ));

Second stream

List<Token> tokenValues = tokens.getColumnFamilies().stream()
            .filter(family -> family.getName().equals("second_family"))
            .findAny()
            .map(columns -> columns.getColumns().stream()).get()
            .map(token -> {
                return Token.builder()
                    .qualifier(token.getPrefix())
                    .raw(rawMapping.get(token.getPrefix()))
                    .token(token.getValue())
                    .build();
            })
            .collect(Collectors.toList());

Basically tokens is a list which has two column family, my goal is to create a list which will combine the value of the two-column family based on their qualifier. The first stream is storing the first column family into a map. The second stream is traversing the second family and getting the value thru the map using the qualifier and storing it into a new list.

1 Answers

you can use double filtering and then later you might use a flat map then to get a list:

Map<String, String> tokenvalues =    tokens.getColumnFamilies().stream()
          .filter(family -> family.getName().equals("first_family"))
           .filter(family -> family.getName().equals("second_family"))
          .map(columns -> columns.getColumns().stream())
       //etc..
.stream()
      .flatMap(Collection::stream)
      .collect(Collectors.toList()));

you can remake a stream out of it inline

https://www.baeldung.com/java-difference-map-and-flatmap

Related