我一直在努力学习Java 8的新功能接口功能,而且我在重构我之前编写的代码时遇到了一些困难.
作为测试用例的一部分,我想在Map结构中存储一个读取名称列表,以便检查这些读取是否已在后续的代码段中“修复”.我正在转换现有的地图>数据结构.我将这个数据结构弄平的原因是因为在后续分析中不需要原始Map的外部“String”键(我在将它们合并到中间数据之前用它来隔离来自不同源的数据).这是我原来的程序逻辑:
public class MyClass {
private Map> anchorLookup;
...
public void CheckMissingAnchors(...){
Map 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
}
}
我试图重构代码以使用功能接口;但是,我从我的IDE(运行Java 1.8.0_05的Netbeans 8.0 Patch 2)中收到错误:
public class MyClass {
private Map> anchorLookup;
...
public void CheckMissingAnchors(...){
Map anchorfound = anchorLookup.keySet()
.stream()
.map((s) -> anchorlookup.get(s).keySet()) // at this point I am expecting a
// Stream> 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>
.collect(Collectors.toMap((s) -> s, (s) -> false);
// I receive an error for the preceding method call, as Stream> cannot be
// converted to type String
...
}
}
有没有更好的方法使用Collection方法创建“anchorfound”映射,还是vanilla Java“foreach”结构是生成此数据结构的最佳方法?
我为代码中的任何明显错误道歉.我的正式培训不是计算机科学,但我想更多地了解Java的函数式编程概念的实现.