gpt4 book ai didi

Java 8 Map KeySet Stream 无法按预期在 Collector 中使用

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:10:04 25 4
gpt4 key购买 nike

我一直在努力学习 Java 8 的函数式接口(interface)新特性,而我在重构之前编写的代码时遇到了一些困难。

作为测试用例的一部分,我想将读取名称列表存储在 Map 结构中,以便检查这些读取是否已在后续代码部分中“修复”。我正在从现有的 Map> 数据结构进行转换。我之所以扁平化这个数据结构是因为在后续分析中不需要原始Map的外部“String”键(我用它来隔离来自不同来源的数据,然后再将它们合并到中间数据中)。这是我原来的程序逻辑:

public class MyClass {
private Map<String, Map<String, Short>> anchorLookup;
...
public void CheckMissingAnchors(...){
Map<String, Boolean> anchorfound = new HashMap<>();

// My old logic used the foreach syntax to populate the "anchorfound" map
for(String rg : anchorLookup.keySet()){
for(String clone : anchorLookup.get(rg).keySet()){
anchorfound.put(clone, false);
}
}
...
// Does work to identify the read name in the file. If found, the boolean in the map
// is set to "true." Afterwards, the program prints the "true" and "false" counts in
// the map
}
}

我试图重构代码以使用函数式接口(interface);但是,我的 IDE(运行 Java 1.8.0_05 的 Netbeans 8.0 补丁 2)出现错误:

public class MyClass {
private Map<String, Map<String, Short>> anchorLookup;
...
public void CheckMissingAnchors(...){

Map<String, Boolean> anchorfound = anchorLookup.keySet()
.stream()
.map((s) -> anchorlookup.get(s).keySet()) // at this point I am expecting a
// Stream<Set<String>> which I thought could be "streamed" for the collector method
// ; however, my IDE does not allow me to select the "stream()" method
.sequential() // this still gives me a Stream<Set<String>>
.collect(Collectors.toMap((s) -> s, (s) -> false);
// I receive an error for the preceding method call, as Stream<Set<String>> cannot be
// converted to type String
...
}
}

是否有更好的方法使用 Collection 方法创建“anchorfound” map ,或者普通 Java“foreach”结构是否是生成此数据结构的最佳方式?

对于我的代码中的任何明显错误,我深表歉意。我的正式培训不是计算机科学,但我想更多地了解 Java 对函数式编程概念的实现。

最佳答案

我相信你需要的是一个 flatMap。

通过这种方式,您可以将外部映射的每个键转换为相应内部映射的键流,然后将它们展平为单个字符串流。

public class MyClass {
private Map<String, Map<String, Short>> anchorLookup;
...
public void CheckMissingAnchors(...){

Map<String, Boolean> anchorfound = anchorLookup.keySet()
.stream()
.flatMap(s -> anchorlookup.get(s).keySet().stream())
.collect(Collectors.toMap((s) -> s, (s) -> false);
...
}
}

关于Java 8 Map KeySet Stream 无法按预期在 Collector 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24940742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com