Stream流使用

常用遍历方式

  1. // forEach()方法:void forEach(Consumer< ? super T> action);
  2. // peek()方法:Stream peek(Consumer< ? super T> action);
  3. List<String> list=...
  4. // 传统for循环
  5. for (String s : list) {
  6. System.out.println(s);
  7. }
  8. // 使用forEach(结束操作),对集合的修改不会影响原集合
  9. list.stream().forEach(x -> {
  10. System.out.println(x);
  11. });
  12. // 使用peek(中间操作),对集合的修改也会体现在原集合中
  13. list = list.stream().peek(x -> {System.out.println(x);}).collect(Collectors.toList());

1.filter过滤(惰性求值)

filter 只刻画出了 Stream,但没有产生新的集合。像 filter 这样只描述 Stream,最终不产生新集合的方法叫作惰性求值方法;而像 collect(Collectors.toList())这样 最终会从 Stream 产生值的方法叫作及早求值方法

  1. public class TestFilter {
  2.   public static void main(String[] args) {
  3.     List<Person> persionList = new ArrayList<Person>();
  4.     persionList.add(new Person(1, "张三", "男", 8));
  5.     persionList.add(new Person(2, "小小", "女", 2));
  6.     persionList.add(new Person(3, "李四", "男", 25));
  7.     persionList.add(new Person(4, "王五", "女", 8));
  8.     persionList.add(new Person(5, "赵六", "女", 25));
  9.     persionList.add(new Person(6, "大大", "男", 65));
  10.     //1、查找年龄大于20岁的人数
  11.     long age=persionList.stream().filter(p->p.getAge()>20).count();
  12.     System.out.println(age);
  13.     //2、查找年龄大于20岁,性别为男的人数
  14.     List<Person> ageList=persionList.stream().filter(p->p.getAge()>20).filter(p->"男".equals(p.getSex())).collect(Collectors.toList());
  15.     System.out.println(ageList.size());
  16. //3、查找年龄大于20岁的男性 或 年龄大于18岁的女性人数
  17. List<Person> ageList=persionList.stream().filter(p -> (p.getAge()>20 && "男".equals(p.getSex())) || (p.getAge()>18 && "女".equals(p.getSex()))).collect(Collectors.toList());
  18. System.out.println(ageList.size());
  19.     //4、过滤掉 姓名、性别、年龄 均相同的重复项
  20.     List<Person> ageList=persionList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> p.getName() + ";" + p.getSex() + ";" + p.getAge()))), ArrayList::new));
  21.     System.out.printIn(ageList.size());
  22.   }
  23. }

2.map转换(map, mapToInt、mapToLong、mapToDouble)

转换流,将一种类型的流转换为另外一种流。(mapToInt、mapToLong、mapToDouble 返回int、long、double基本类型对应的Stream)

  1. public class Person {
  2. private Integer id;
  3. private String name;
  4. private String sex;
  5. private Integer age;
  6. //提供get,set,和满参构造函数
  7. }
  8. public class TestMap {
  9.   public static void main(String[] args) {
  10.     List<Person> persionList = new ArrayList<Person>();
  11.     persionList.add(new Person(1,"张三","男",38));
  12.     persionList.add(new Person(2,"小小","女",2));
  13.     persionList.add(new Person(3,"李四","男",65));
  14.     persionList.add(new Person(4,"王五","女",20));
  15.     persionList.add(new Person(5,"赵六","男",38));
  16.     persionList.add(new Person(6,"大大","男",65));
  17.     //1、只取出该集合中所有姓名组成一个新集合
  18.     List<String> nameList=persionList.stream().map(Person::getName).collect(Collectors.toList()); //未去重
  19.     List<String> nameList=persionList.stream().map(Person::getName).distinct().collect(Collectors.toList()); //去重
  20.     System.out.println(nameList.toString());
  21.     //2、只取出该集合中所有id组成一个新集合
  22.     List<Integer> idList=persionList.stream().mapToInt(Person::getId).boxed().collect(Collectors.toList());
  23.     System.out.println(idList.toString());
  24.     //3、list转map,key值为id,value为Person对象
  25.     Map<Integer, Person> personmap = persionList.stream().collect(Collectors.toMap(Person::getId, person -> person));
  26.     System.out.println(personmap.toString());
  27.     //4、list转map,key值为id,value为name
  28.     Map<Integer, String> namemap = persionList.stream().collect(Collectors.toMap(Person::getId, Person::getName));
  29.     System.out.println(namemap.toString());
  30.     //5、进行map集合存放,key为age值 value为Person对象 它会把相同age的对象放到一个集合中
  31.     Map<Integer, List<Person>> ageMap = persionList.stream().collect(Collectors.groupingBy(Person::getAge));
  32.     System.out.println(ageMap.toString());
  33.     //6、获取最小年龄
  34.     Integer ageMin = persionList.stream().mapToInt(Person::getAge).min().getAsInt();
  35.     System.out.println("最小年龄为: "+ageMin);
  36.     //7、获取最大年龄
  37.     Integer ageMax = persionList.stream().mapToInt(Person::getAge).max().getAsInt();
  38.     System.out.println("最大年龄为: "+ageMax);
  39.     //8、集合年龄属性求和
  40.     Integer ageAmount = persionList.stream().mapToInt(Person::getAge).sum();
  41.     System.out.println("年龄总和为: "+ageAmount);
  42. //9、不改变原本的集合修改集合
  43. List<Person> lists = persionList.stream().map(item -> {
  44. Person person = new Person();
  45. person.setName("修改集合");
  46. return person;
  47. }).collect(Collectors.toList());
  48. //10 改变原来员工集合的方式
  49. List<Person> personListNew2 = personList.stream().map(person -> {
  50. person.setSalary(person.getSalary() + 10000);
  51. return person;
  52. }).collect(Collectors.toList());
  53.   }
  54. }

4.排序

sorted() 排序方法

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Person> persionList = new ArrayList<Person>();
  4. persionList.add(new Person(1, "张三", "男", 8));
  5. persionList.add(new Person(2, "小小", "女", 2));
  6. persionList.add(new Person(3, "李四", "男", 25));
  7. persionList.add(new Person(4, "王五", "女", 8));
  8. persionList.add(new Person(5, "赵六", "女", 25));
  9. persionList.add(new Person(6, "大大", "男", 65));
  10. //根据年龄升序
  11. persionList = persionList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
  12. persionList = persionList.stream().sorted(Comparator.comparingInt(x -> x.getAge())).collect(Collectors.toList());
  13. persionList = persionList.stream().sorted((a, b) -> a.getAge().compareTo(b.getAge())).collect(Collectors.toList());
  14. //根据年龄降序
  15. persionList = persionList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
  16. persionList = persionList.stream().sorted((a, b) -> b.getAge().compareTo(a.getAge())).collect(Collectors.toList());
  17. //根据年龄降序,年龄相同的再根据id升序
  18. persionList = persionList.stream().sorted(Comparator.comparing(Person::getAge).reversed().thenComparing(Person::getId)).collect(Collectors.toList());
  19. }
  20. }

Stream 按组分别统计

  1. Map<Long, List<ActivityGift>> groupGifts = gifts.stream().collect(Collectors.groupingBy(ActivityGift::getActivityId, Collectors.toList()));

Stream 按某个值相等统计

  1. List<Activity> activities = activityMapper.selectBatchIds(groupGifts.keySet());
  2. activities = activities.stream().filter(activity -> activity.getStatus() == status).collect(Collectors.toList());

求list集合中所有value的值

  1. list.stream().mapToDouble(Px::getValue).sum()

求某一属性集合

  1. Set<String> name= syDailyStatements.stream().map(YcDailyStatement::getSiteName).collect(Collectors.toSet());

利用siteName 把list分成集合组

  1. Map<String, List<RankVo2>> collect = rankVo2pm25List.stream().collect(Collectors.groupingBy(RankVo2::getSiteName));

求平均值

  1. List<DayData> pm25List = dayData.stream().filter(s -> s.getPm25() != null).collect(Collectors.toList());
  2. if (pm25List != null && pm25List.size() > 0) {
  3. double pm25 = pm25List.stream().mapToDouble(DayData::getPm25).average().getAsDouble() * 1000;
  4. double getint = getint(pm25, 0);
  5. rateData1.setPm25Rate(getint);
  6. }

求最大值

  1. double max = hourData1.stream().filter(s -> s.getName() != null && s.getName().equals("PM10")).mapToDouble(HourData::getVal).summaryStatistics().getMax()*1000;
  2. List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6);
  3. // 自然排序
  4. Optional<Integer> max = list.stream().max(Integer::compareTo);
  5. // 自定义排序
  6. Optional<Integer> max2 = list.stream().max(new Comparator<Integer>() {
  7. @Override
  8. public int compare(Integer o1, Integer o2) {
  9. return o1.compareTo(o2);
  10. }
  11. });
  12. System.out.println("自然排序的最大值:" + max.get());
  13. System.out.println("自定义排序的最大值:" + max2.get());
  14. // 求工资最高的
  15. Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary));
  16. //获取String集合中最长的元素
  17. List list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
  18. Optional<String> max = list.stream().max(Comparator.comparing(String::length));
  19. System.out.println("最长的字符串:" + max.get());
  20. // 计算Integer集合中大于6的元素的个数。
  21. list.stream().filter(x -> x > 6).count();

选出不同的

  1. List<String> prices = new LinkedList<>();
  2. prices.stream().distinct().collect(Collectors.toList());

求某一个属性去掉相同的元素

  1. // id是判断是否重复的条件
  2. List<Goods> goodsList = allocationGoodsList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(Goods::getRbtPreparation))), ArrayList::new));

求多个属性去掉相同的元素

  1. // 可以多条件去重
  2. ArrayList<PatentDto> collect1 = patentDtoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList::new)

比较过滤

  1. Goods goods = searchResult.getGoodsList().stream().filter(e -> e.getPrices().get(priceId).compareTo(supplyMoney) == 0).findAny().orElse(null);

集合是否包含字符串

  1. KeywordConst.KW_NO.stream().anyMatch(message::contains)

求两个集合对象的交集、并集、差集、去重

  1. package com.ymdd.galaxy.appmanage.core.appauth.service;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import static java.util.stream.Collectors.toList;
  5. public class Test {
  6. public static void main(String[] args) {
  7. List<String> list1 = new ArrayList<String>();
  8. list1.add("1");
  9. list1.add("2");
  10. list1.add("3");
  11. list1.add("5");
  12. list1.add("6");
  13. List<String> list2 = new ArrayList<String>();
  14. list2.add("2");
  15. list2.add("3");
  16. list2.add("7");
  17. list2.add("8");
  18. // 交集
  19. List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
  20. System.out.println("---交集 intersection---");
  21. intersection.parallelStream().forEach(System.out :: println);
  22. // 差集 (list1 - list2)
  23. List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
  24. System.out.println("---差集 reduce1 (list1 - list2)---");
  25. reduce1.parallelStream().forEach(System.out :: println);
  26. // 差集 (list2 - list1)
  27. List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
  28. System.out.println("---差集 reduce2 (list2 - list1)---");
  29. reduce2.parallelStream().forEach(System.out :: println);
  30. // 并集
  31. List<String> listAll = list1.parallelStream().collect(toList());
  32. List<String> listAll2 = list2.parallelStream().collect(toList());
  33. listAll.addAll(listAll2);
  34. System.out.println("---并集 listAll---");
  35. listAll.parallelStream().forEachOrdered(System.out :: println);
  36. // 去重并集
  37. List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
  38. System.out.println("---得到去重并集 listAllDistinct---");
  39. listAllDistinct.parallelStream().forEachOrdered(System.out :: println);
  40. System.out.println("---原来的List1---");
  41. list1.parallelStream().forEachOrdered(System.out :: println);
  42. System.out.println("---原来的List2---");
  43. list2.parallelStream().forEachOrdered(System.out :: println);
  44. }
  45. }

字符串排序

  1. return registerList.stream().map(item -> {
  2. item.setCheckoutProductDetails(detailGroup.get(item.getId()));
  3. final String checkoutReportAttachIds = item.getCheckoutReportAttachIds();
  4. if (StringUtils.isNotEmpty(checkoutReportAttachIds)) {
  5. final String attachesStr = Arrays.stream(checkoutReportAttachIds.split(",")).filter(str -> StringUtils.isNotEmpty(str) && !"undefined".equals(str.toLowerCase())).collect(Collectors.joining(","));
  6. item.setSysAttaches(sysAttachMapper.getList(attachesStr));
  7. }
  8. return QsCheckoutRegisterService.translationCheckoutRegisterDict(item);
  9. }).sorted(Comparator.comparing(QsCheckoutRegister::getReCheckCnt, Comparator.comparingInt(p -> Integer.parseInt(String.valueOf(p))))).collect(Collectors.toList());

Collectors.summingDouble() 方法将流中的所有元素视为 Double类型,并计算所有元素的总和 ( sum )

  1. List<Double> list = Arrays.asList(1.1, 2.2, 3.3, 4.4);
  2. Double sum = list.stream().collect(Collectors.summingDouble(i -> {
  3. System.out.println("i -> " + i);
  4. return i;
  5. }));
  6. System.out.println(sum);