Stream流使用
常用遍历方式
// forEach()方法:void forEach(Consumer< ? super T> action);// peek()方法:Stream peek(Consumer< ? super T> action);List<String> list=...// 传统for循环for (String s : list) {System.out.println(s);}// 使用forEach(结束操作),对集合的修改不会影响原集合list.stream().forEach(x -> {System.out.println(x);});// 使用peek(中间操作),对集合的修改也会体现在原集合中list = list.stream().peek(x -> {System.out.println(x);}).collect(Collectors.toList());
1.filter过滤(惰性求值)
filter 只刻画出了 Stream,但没有产生新的集合。像 filter 这样只描述 Stream,最终不产生新集合的方法叫作惰性求值方法;而像 collect(Collectors.toList())这样 最终会从 Stream 产生值的方法叫作及早求值方法
public class TestFilter {public static void main(String[] args) {List<Person> persionList = new ArrayList<Person>();persionList.add(new Person(1, "张三", "男", 8));persionList.add(new Person(2, "小小", "女", 2));persionList.add(new Person(3, "李四", "男", 25));persionList.add(new Person(4, "王五", "女", 8));persionList.add(new Person(5, "赵六", "女", 25));persionList.add(new Person(6, "大大", "男", 65));//1、查找年龄大于20岁的人数long age=persionList.stream().filter(p->p.getAge()>20).count();System.out.println(age);//2、查找年龄大于20岁,性别为男的人数List<Person> ageList=persionList.stream().filter(p->p.getAge()>20).filter(p->"男".equals(p.getSex())).collect(Collectors.toList());System.out.println(ageList.size());//3、查找年龄大于20岁的男性 或 年龄大于18岁的女性人数List<Person> ageList=persionList.stream().filter(p -> (p.getAge()>20 && "男".equals(p.getSex())) || (p.getAge()>18 && "女".equals(p.getSex()))).collect(Collectors.toList());System.out.println(ageList.size());//4、过滤掉 姓名、性别、年龄 均相同的重复项List<Person> ageList=persionList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> p.getName() + ";" + p.getSex() + ";" + p.getAge()))), ArrayList::new));System.out.printIn(ageList.size());}}
2.map转换(map, mapToInt、mapToLong、mapToDouble)
转换流,将一种类型的流转换为另外一种流。(mapToInt、mapToLong、mapToDouble 返回int、long、double基本类型对应的Stream)
public class Person {private Integer id;private String name;private String sex;private Integer age;//提供get,set,和满参构造函数}public class TestMap {public static void main(String[] args) {List<Person> persionList = new ArrayList<Person>();persionList.add(new Person(1,"张三","男",38));persionList.add(new Person(2,"小小","女",2));persionList.add(new Person(3,"李四","男",65));persionList.add(new Person(4,"王五","女",20));persionList.add(new Person(5,"赵六","男",38));persionList.add(new Person(6,"大大","男",65));//1、只取出该集合中所有姓名组成一个新集合List<String> nameList=persionList.stream().map(Person::getName).collect(Collectors.toList()); //未去重List<String> nameList=persionList.stream().map(Person::getName).distinct().collect(Collectors.toList()); //去重System.out.println(nameList.toString());//2、只取出该集合中所有id组成一个新集合List<Integer> idList=persionList.stream().mapToInt(Person::getId).boxed().collect(Collectors.toList());System.out.println(idList.toString());//3、list转map,key值为id,value为Person对象Map<Integer, Person> personmap = persionList.stream().collect(Collectors.toMap(Person::getId, person -> person));System.out.println(personmap.toString());//4、list转map,key值为id,value为nameMap<Integer, String> namemap = persionList.stream().collect(Collectors.toMap(Person::getId, Person::getName));System.out.println(namemap.toString());//5、进行map集合存放,key为age值 value为Person对象 它会把相同age的对象放到一个集合中Map<Integer, List<Person>> ageMap = persionList.stream().collect(Collectors.groupingBy(Person::getAge));System.out.println(ageMap.toString());//6、获取最小年龄Integer ageMin = persionList.stream().mapToInt(Person::getAge).min().getAsInt();System.out.println("最小年龄为: "+ageMin);//7、获取最大年龄Integer ageMax = persionList.stream().mapToInt(Person::getAge).max().getAsInt();System.out.println("最大年龄为: "+ageMax);//8、集合年龄属性求和Integer ageAmount = persionList.stream().mapToInt(Person::getAge).sum();System.out.println("年龄总和为: "+ageAmount);//9、不改变原本的集合修改集合List<Person> lists = persionList.stream().map(item -> {Person person = new Person();person.setName("修改集合");return person;}).collect(Collectors.toList());//10 改变原来员工集合的方式List<Person> personListNew2 = personList.stream().map(person -> {person.setSalary(person.getSalary() + 10000);return person;}).collect(Collectors.toList());}}
4.排序
sorted() 排序方法
public class Test {public static void main(String[] args) {List<Person> persionList = new ArrayList<Person>();persionList.add(new Person(1, "张三", "男", 8));persionList.add(new Person(2, "小小", "女", 2));persionList.add(new Person(3, "李四", "男", 25));persionList.add(new Person(4, "王五", "女", 8));persionList.add(new Person(5, "赵六", "女", 25));persionList.add(new Person(6, "大大", "男", 65));//根据年龄升序persionList = persionList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());persionList = persionList.stream().sorted(Comparator.comparingInt(x -> x.getAge())).collect(Collectors.toList());persionList = persionList.stream().sorted((a, b) -> a.getAge().compareTo(b.getAge())).collect(Collectors.toList());//根据年龄降序persionList = persionList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());persionList = persionList.stream().sorted((a, b) -> b.getAge().compareTo(a.getAge())).collect(Collectors.toList());//根据年龄降序,年龄相同的再根据id升序persionList = persionList.stream().sorted(Comparator.comparing(Person::getAge).reversed().thenComparing(Person::getId)).collect(Collectors.toList());}}
Stream 按组分别统计
Map<Long, List<ActivityGift>> groupGifts = gifts.stream().collect(Collectors.groupingBy(ActivityGift::getActivityId, Collectors.toList()));
Stream 按某个值相等统计
List<Activity> activities = activityMapper.selectBatchIds(groupGifts.keySet());activities = activities.stream().filter(activity -> activity.getStatus() == status).collect(Collectors.toList());
求list集合中所有value的值
list.stream().mapToDouble(Px::getValue).sum()
求某一属性集合
Set<String> name= syDailyStatements.stream().map(YcDailyStatement::getSiteName).collect(Collectors.toSet());
利用siteName 把list分成集合组
Map<String, List<RankVo2>> collect = rankVo2pm25List.stream().collect(Collectors.groupingBy(RankVo2::getSiteName));
求平均值
List<DayData> pm25List = dayData.stream().filter(s -> s.getPm25() != null).collect(Collectors.toList());if (pm25List != null && pm25List.size() > 0) {double pm25 = pm25List.stream().mapToDouble(DayData::getPm25).average().getAsDouble() * 1000;double getint = getint(pm25, 0);rateData1.setPm25Rate(getint);}
求最大值
double max = hourData1.stream().filter(s -> s.getName() != null && s.getName().equals("PM10")).mapToDouble(HourData::getVal).summaryStatistics().getMax()*1000;List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6);// 自然排序Optional<Integer> max = list.stream().max(Integer::compareTo);// 自定义排序Optional<Integer> max2 = list.stream().max(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o1.compareTo(o2);}});System.out.println("自然排序的最大值:" + max.get());System.out.println("自定义排序的最大值:" + max2.get());// 求工资最高的Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary));//获取String集合中最长的元素List list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");Optional<String> max = list.stream().max(Comparator.comparing(String::length));System.out.println("最长的字符串:" + max.get());// 计算Integer集合中大于6的元素的个数。list.stream().filter(x -> x > 6).count();
选出不同的
List<String> prices = new LinkedList<>();prices.stream().distinct().collect(Collectors.toList());
求某一个属性去掉相同的元素
// id是判断是否重复的条件List<Goods> goodsList = allocationGoodsList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(Goods::getRbtPreparation))), ArrayList::new));
求多个属性去掉相同的元素
// 可以多条件去重ArrayList<PatentDto> collect1 = patentDtoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList::new)
比较过滤
Goods goods = searchResult.getGoodsList().stream().filter(e -> e.getPrices().get(priceId).compareTo(supplyMoney) == 0).findAny().orElse(null);
集合是否包含字符串
KeywordConst.KW_NO.stream().anyMatch(message::contains)
求两个集合对象的交集、并集、差集、去重
package com.ymdd.galaxy.appmanage.core.appauth.service;import java.util.ArrayList;import java.util.List;import static java.util.stream.Collectors.toList;public class Test {public static void main(String[] args) {List<String> list1 = new ArrayList<String>();list1.add("1");list1.add("2");list1.add("3");list1.add("5");list1.add("6");List<String> list2 = new ArrayList<String>();list2.add("2");list2.add("3");list2.add("7");list2.add("8");// 交集List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());System.out.println("---交集 intersection---");intersection.parallelStream().forEach(System.out :: println);// 差集 (list1 - list2)List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());System.out.println("---差集 reduce1 (list1 - list2)---");reduce1.parallelStream().forEach(System.out :: println);// 差集 (list2 - list1)List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());System.out.println("---差集 reduce2 (list2 - list1)---");reduce2.parallelStream().forEach(System.out :: println);// 并集List<String> listAll = list1.parallelStream().collect(toList());List<String> listAll2 = list2.parallelStream().collect(toList());listAll.addAll(listAll2);System.out.println("---并集 listAll---");listAll.parallelStream().forEachOrdered(System.out :: println);// 去重并集List<String> listAllDistinct = listAll.stream().distinct().collect(toList());System.out.println("---得到去重并集 listAllDistinct---");listAllDistinct.parallelStream().forEachOrdered(System.out :: println);System.out.println("---原来的List1---");list1.parallelStream().forEachOrdered(System.out :: println);System.out.println("---原来的List2---");list2.parallelStream().forEachOrdered(System.out :: println);}}
字符串排序
return registerList.stream().map(item -> {item.setCheckoutProductDetails(detailGroup.get(item.getId()));final String checkoutReportAttachIds = item.getCheckoutReportAttachIds();if (StringUtils.isNotEmpty(checkoutReportAttachIds)) {final String attachesStr = Arrays.stream(checkoutReportAttachIds.split(",")).filter(str -> StringUtils.isNotEmpty(str) && !"undefined".equals(str.toLowerCase())).collect(Collectors.joining(","));item.setSysAttaches(sysAttachMapper.getList(attachesStr));}return QsCheckoutRegisterService.translationCheckoutRegisterDict(item);}).sorted(Comparator.comparing(QsCheckoutRegister::getReCheckCnt, Comparator.comparingInt(p -> Integer.parseInt(String.valueOf(p))))).collect(Collectors.toList());
Collectors.summingDouble() 方法将流中的所有元素视为 Double类型,并计算所有元素的总和 ( sum )
List<Double> list = Arrays.asList(1.1, 2.2, 3.3, 4.4);Double sum = list.stream().collect(Collectors.summingDouble(i -> {System.out.println("i -> " + i);return i;}));System.out.println(sum);
