Java8新特性Stream流应用示例

时间:2023-12-23 14:10:50

Java8新特性介绍

过滤集合

 List<String> newList = list.stream().filter(item -> item != null).collect(Collectors.toList());

找出并返回集合中重复的元素

ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(1);
list.add(2);
list.add(3);
Set<Integer> collect = list.stream().filter(i -> list.stream().filter(i::equals).count() > 1).collect(Collectors.toSet());

返回对象数组某一元素构成的集合

	List<String> list1 = list.stream().map(User::getUsername).collect(Collectors.toList());

根据某一元素去重

 ArrayList<EmdBageOrderListDto> distinctList = list.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getUsername))), ArrayList::new));

根据集合某个属性分组并存入map

  Map<String, List<User>> bageOrderMap = list.stream().collect(Collectors.groupingBy(User::getUsername));

类型转换

List转String

String str = list.stream().collect(Collectors.joining(","))

List<String>List<Integer>

//方法一
List<Integer> intList = strList.stream().map(Integer::parseInt).collect(Collectors.toList()); //方法二
List<Integer> intStream = strList.stream().mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());