是否有更好的方法来计算 map 中所有列表的大小?那么firstList.size() + secondaryList.size()
?
我已经这样做了,但是创建一个列表只是为了计数并不感觉是正确的方法..
public static void main(String[] args) {
List<String> firstList = new ArrayList<>();
firstList.add("first");
List<String> secondList = new ArrayList<>();
secondList.add("second");
Map<String, List<String>> myMap = new HashMap<>();
myMap.put("one", firstList);
myMap.put("two", secondList);
int size = myMap.entrySet().stream()
.map(entry -> entry.getValue())
.flatMap(list -> list.stream())
.collect(Collectors.toList())
.size();
System.out.println("Size of all elements in map is:" + size);
}
最佳答案
这至少更具可读性
int size = myMap.values().stream()
.mapToInt(Collection::size)
.sum();
或者,如果您想看起来像函数式编程大师,请使用:
int size2 = myMap.values().stream()
.reduce(0, (acc, val) -> acc + val.size(), Integer::sum);
编辑:使用.values()
:]
关于java - 计算要列表的字符串映射中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32000111/