有没有更好的方法来计算地图中所有列表的大小?那么firstList.size() + secondList.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);
}
答案 0 :(得分:7)
这至少更具可读性
int size = myMap.values().stream()
.mapToInt(Collection::size)
.sum();
或者如果你想看起来像一个函数式编程大师,请使用:
int size2 = myMap.values().stream()
.reduce(0, (acc, val) -> acc + val.size(), Integer::sum);
编辑:使用.values()
:
答案 1 :(得分:3)
之前的两个答案都很好,但可以通过直接values()
来缩短,而不是迭代entrySet()
:
// Streaming version
int size = myMap.values().stream()
.mapToInt(list -> list.size())
.sum();
// Standard loop version
int size = 0;
for (List<String> list : myMap.values())
size += list.size();
答案 2 :(得分:-1)
另一种方式:
private static int size = 0;
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);
myMap.values().forEach(value -> {size += value.size();});
System.out.println("Size of all elements in map is:" + size);
}