Java8 Stream应用:Map合并、过滤、遍历、values int求和等

1. Java多个Map合并

// 多个Map, 根据key相同的,value累积求和;
public static Map mapCombine(List<Map<Long,Integer>> list) {
	Map<Long, Integer> map = new HashMap<>();
	for (Map<Long,Integer> m : list) {
	    Iterator<Long> it = m.keySet().iterator();
	    while (it.hasNext()) {
	        Long key = it.next();
	        if (!map.containsKey(key)) {
	            map.put(key, m.get(key));
	        } else {
	            map.put(key,(map.get(key)+m.get(key)));
	        }
	    }
	}
	return map;
}

2. Java中 map.values(Integer) 求和:

Integer totalCount = map.values().stream().mapToInt(Integer::intValue).sum(); //values求和

3. Map遍历:

map.entrySet().stream().forEach(x -> {
	System.out.println("key: "+x.getKey()+", value: "+x.getValue());
});

4. Map 过滤:

result = map.entrySet().stream()
	.filter(map -> "hello world".equals(map.getValue()))
	.map(map -> map.getValue())
	.collect(Collectors.joining()
);

参考:

https://blog.csdn.net/qq_24877569/article/details/52187388

你可能感兴趣的:(大数据,JAVA,java,Java8,stream,过滤,遍历)