英文:
Java Stream - Combine filter and collect
问题
ColumnFamily column = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.findAny()
.get();
Map<String, String> tokenized = column.getColumns().stream()
.collect(Collectors.toMap(
Column::getQualifier,
Column::getValue
));
Is there a way I can combine these two streams into one? I am using the first stream to filter and find on my nested list, and using the second stream to create a map based on the result of the stream. I am wondering if there's a way I could have done this using a single stream.
Something like this
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.flatMap(family -> family.getColumns().stream())
.collect(Collectors.toMap(
Column::getQualifier,
Column::getValue
));
英文:
ColumnFamily column = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.findAny()
.get();
Map<String, String> tokenized = column.getColumns().stream()
.collect(Collectors.toMap(
Column::getQualifier,
Column::getValue
));
Is there a way I can combine these two streams into one? I am using the first stream to filter and find on my nested list, and using the second stream to create a map based on the result of the stream. I am wondering if there's a way I could have done this using a single stream.
Something like this
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.collect(Collectors.toMap(
//
));
答案1
得分: 2
你可以使用 flatMap
来获取嵌套的 Stream
并展平结构:
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.limit(1) // 相当于 findAny
.flatMap(cf -> cf.getColumns().stream())
.collect(Collectors.toMap(
Column::getQualifier,
Column::getValue
));
英文:
You can use flatMap
to get nested Stream
and flatten the structure:
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.limit(1) // equivalent of findAny
.flatMap(cf -> cf.getColumns().stream())
.collect(Collectors.toMap(
Column::getQualifier,
Column::getValue
));
答案2
得分: 0
使用 Optional#map()
并结合:
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.findAny()
.map(cf -> cf.getColumns().stream()).get()
.collect(Collectors.toMap(Column::getQualifier, Column::getValue));
英文:
Use Optional#map()
and combine
Map<String, String> tokenized = tokens.getColumnFamilies().stream()
.filter(family -> family.getName().equals("this_family"))
.findAny()
.map(cf -> cf.getColumns().stream()).get()
.collect(Collectors.toMap(Column::getQualifier, Column::getValue));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论