如何使用Java Streams从HashMaps的ArrayList中获取字符串

Pra*_*dra 2 java hashmap java-stream

我有一个数据结构 - ArrayList>这就是我需要做的 -

ArrayList<HashMap<String, String>> optMapList;
//populated optMapList with some code. Not to worry abt this

List<String> values = new ArrayList<String>();

for(HashMap<String,String> entry: optMapList){
    values.add(entry.get("optValue"));
}
Run Code Online (Sandbox Code Playgroud)

我们如何使用Java Streams实现相同的目标?

Eug*_*ene 5

 optMapList.stream()
           .filter(Objects:nonNull) // potentially filter null maps
           .map(m -> m.get("optValue"))
           .filter(Objects::nonNull) // potentially filter null values form the map 
           // .collect(Collectors.toCollection(ArrayList::new)) 
           .collect(Collectors.toList())
Run Code Online (Sandbox Code Playgroud)

  • 插入虚假的"null"检查会带来更多弊大于利.原始代码表明OP假定映射永远不会为"null",因此当这个假设不成立时代码应该大声失败,而不是静默地跳过条目.在值的情况下,我们不知道它们是否应该始终存在且非"空"或者是否可能在结果列表中具有"null"条目.在任何一种情况下,原始代码都保证源列表位置与结果列表位置匹配,插入过滤器会破坏此不变量. (2认同)