简体   繁体   English

Java Stream - 合并两个流

[英]Java Stream - Combine Two Streams

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 .基本上标记是一个具有两个列族的列表,我的目标是创建一个列表,该列表将根据它们的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.第二个流正在遍历第二个系列并使用限定符通过映射获取值并将其存储到新列表中。

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 https://www.baeldung.com/java-difference-map-and-flatmap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM