package src;
import java.util.*;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class MapTest {
public static void test(){
//stream
Map<Integer,String> map=new HashMap<Integer,String>();
for (int i = 1; i < 20; i++) {
map.put(i,"a"+i);
}
//1.转换key列表
List<String> valuesList=map.values().stream().collect(Collectors.toList());
for (String a : valuesList) System.out.println(a);
System.out.println("-------------------");
//2.转换为value列表
List key_list=map.keySet().stream().collect(Collectors.toList());
for (Object b:key_list) {
System.out.println(b);
}
//3.按要求过滤
System.out.println("-------------------");
List Filter_key_list=map.keySet().stream().filter(m->m>10).collect(Collectors.toList());
for (Object a:Filter_key_list) {
System.out.println(a);
}
System.out.println("-------------------");
//4.按要求过滤--过滤后仍然是map
Map<Integer,String> ChildMap=map.entrySet().stream().filter(m->m.getKey()>10).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
for(Map.Entry a:ChildMap.entrySet()) System.out.println(a.getKey()+"-"+a.getValue());
System.out.println("-------------------");
//5.求和
int total=map.keySet().stream().mapToInt(Integer::intValue).sum();
System.out.println(total);
//6.排序键值对
System.out.println("-------------------");
List<Integer> collect1 = map.keySet().stream().sorted().collect(Collectors.toList());
for (Integer a:collect1) System.out.println(a);
//降序
List<Map.Entry<Integer,String>> collect2 = map.entrySet().stream()
.sorted(Map.Entry.<Integer,String>comparingByKey().reversed())
.collect(Collectors.toList());
collect2.forEach(m-> System.out.println(m.getKey()+"-"+m.getValue()));
}
public static void test2(){
//7.分组统计
Map<String,String> map=new HashMap();
map.put("张三","1");
map.put("李四","2");
map.put("王五","1");
map.put("赵六","2");
map.put("刘七","3");
Map<String,Long> childmap = map.values().stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
childmap.forEach((m,n)-> System.out.println(m+"-"+n));
}
public static void test3(){
//8.联合操作
Map<String,Integer> salaries=new HashMap<>();//假设这是一个员工薪水的Map
salaries.put("张三",5000);
salaries.put("李四",3000);
salaries.put("王五",5000);
salaries.put("赵六",8000);
salaries.put("刘七",6000);
Map<String,String> departments=new HashMap<>();//假设这是一个员工部门的Map
departments.put("张三","1");
departments.put("李四","2");
departments.put("王五","1");
departments.put("赵六","2");
departments.put("刘七","3");
//输出高新员工,及其部门
Map<String, String> collect = salaries.entrySet().stream().filter(e -> e.getValue() > 5000).map(m -> new AbstractMap.SimpleEntry<>(m.getKey(), departments.get(m.getKey())))
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue
));
collect.forEach((m,n)-> System.out.println(m+"-"+n));
}
public static void main(String[] args){
test3();
}
}