java8stream的⽤法总结
1、遍历map
map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
2、map转list
3、list转map
Map<Integer, String> result1 = list.stream().Map(Hosting::getId, Hosting::getName));
stream中的 filter  map  ⽅法都可以对stream进⾏操作。使⽤collect⽅法可以将stream转换为list和map。
注意:⽤Collectors的toMap⽅法转换List,⼀般会遇到两个问题。⼀个是转换map,key重复问题;另⼀个是空指针异常,即转为map的value是null。
解决⽅法:(分三种,具体哪种看业务需求)
(1)重复时⽤后⾯的value 覆盖前⾯的value
Map<Integer, String> result1 = list.stream().Map(Hosting::getId, Hosting::getName,(key1 , key2)-> key2));
(2)重复时将前⾯的value 和后⾯的value拼接起来;
Map<Integer, String> result1 = list.stream().Map(Hosting::getId, Hosting::getName,(key1 , key2)-> key1+“,”+key2));
(3)重复时将重复key的数据组成集合
Map<Integer, List<String>> map = list.stream().Map(Hosting::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.Name());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
));
System.out.println(map);
4、map将list中的字母转为⼤写:
java stream
List<String> alpha = Arrays.asList("a", "b", "c", "d");
List<String> list = alpha.stream().map(string ->{
String res = UpperCase();
return "stream().map()处理之后:" + res;
}).List());
//list.forEach(System.out::println);
list.stream().forEach(string -> {
System.out.println(System.out::println);
});
运⾏结果:
stream().map()处理之后:A
stream().map()处理之后:B
stream().map()处理之后:C
stream().map()处理之后:D
5、filter去除list中值为null的
Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php");
List<String> result = language.filter(x -> x!=null).List());
List<String> result = language.filter(Objects::nonNull).List());
6、
//List根据某个字段过滤、排序
listStu.stream()
.filter(student -> Sex().equals("⼥"))
.sorted(Comparatorparing(Student::getName))
.List());
//List根据某个字段分组
Map<String,List<Student>> sexGroupMap = listStu.stream()
.upingBy(Student::getSex));
//如果Map中多个名称相同,则studentId⽤逗号间隔
Map<String,String> studentNameIdMap = listStu.stream()
.collect(toMap(Student::getName,Student::getStuId,(s,a)->s+","+a));
7、遍历循环过滤以某个字段分组后的map
//声明⼀个List集合
List<User> list = new ArrayList();
list.add(new User("⼩A",10,"90"));
list.add(new User( "⼩B",20,"23"));
list.add(new User("⼩C",47,"98"));
list.add(new User("⼩C",34,"90"));
Map<String, List<User>> map = list.stream().upingBy(User::getName)); List<Pesron> AA = new ArrayList<>();
map.forEach((key,value) ->{
value.stream().filter(user -> {
Pesron a = new Pesron();
if (Age() > 10 && "23".Score())) {
a.Score());
a.setName(key);
AA.add(a);
}
return true;
}
).List());
System.out.println("key--:"+key+"----value:"+value);
});
System.out.println(AA);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。