java8新特性

时间:2021-07-27 17:44:30

 1、list<Dto>转List<String>

List<String> openIdList = list.stream().map(o -> o.getOpenId()).collect(Collectors.toList());

 2、List转map

Map<String, SearchActivityCustomerResultDto> userMap =
userList
.stream()
.collect(Collectors.toMap(SearchActivityCustomerResultDto::getOpenid, a -> a));

3、groupingBy分组

Map<Integer, List<Apple>> groupBy =
appleList.stream().collect(Collectors.groupingBy(Apple::getId));

4、filter过滤出符合条件的数据

List<Apple> filterList =
appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());

5、排序

//1.jdk8 lambda排序,带参数类型,倒序

appleList.sort(( Apple ord1, Apple ord2) -> ord2.getId().compareTo(ord1.getId()));

//2.jdk8 lambda排序,不带参数类型,倒序

appleList.sort(( ord1, ord2) -> ord2.getId().compareTo(ord1.getId()));

//3.jdk8 升序排序,Comparator提供的静态方法

Collections.sort(appleList, Comparator.comparing(Apple::getId));

//4.jdk8 降序排序,Comparator提供的静态方法

Collections.sort(appleList, Comparator.comparing(Apple::getId).reversed());

//5.jdk8 组合排序,Comparator提供的静态方法,先按Id排序,Id相同的按money排序

Collections.sort(appleList, Comparator.comparing(Apple::getId).thenComparing(Apple::getMoney).reversed());

6、for循环

appleList.stream().forEach(str -> System.out.println(str.getId()+"/" + str.getMoney()));

7、分页

appleList.subList((page - 1) * rows, rows * page);
List<Apple> pagingData = appleList.stream().limit(rows).collect(Collectors.toList());

8、去重

List<Apple> result = appleList.stream().distinct().collect(toList());

//截取前2个元素

List<Apple> pagingData = appleList.stream().limit(2).collect(toList());