集合转换
List转换为Map
// List<Apple> 根据color转换为map
Map<String, List<Apple>> appleMap = apples.stream().collect(groupingBy(Apple::getColor));
// List<Apple> 根据color转换为map<String, Apple>,重复的Color取后者
Map<String, Apple> appleMap = apples.stream().collect(toMap(Apple::getColor, a -> a, (a1, a2) -> a2));
// List<Apple> 根据color转换为map<String, Integer>,重复的Color取后者
Map<String, Integer> map2 = apples.stream().collect(toMap(Apple::getColor, Apple::getWeight, (a1, a2) -> a2));
Map转List
Map<String, Apple> appleMap = apples.stream().collect(toMap(Apple::getColor, a -> a, (a1, a2) -> a2));
// map转List
List<String> colors = appleMap.values().stream().map(Apple::getColor).collect(toList());
Map转Set
Map<String, Apple> appleMap = apples.stream().collect(toMap(Apple::getColor, a -> a, (a1, a2) -> a2));
// map转set
Set<String> set = appleMap.values().stream().map(Apple::getColor).collect(toSet());
网友评论