java stream流常用方法

Stream流用法

    • 1、分组
    • 2、过滤
    • 3、List map互转
    • 4、求和/极值
    • 5、求最大/最小值的对象
    • 6、去重
    • 7、排序
    • 8、拼接
    • 9、统计
    • 10、平均值
    • 11、某个值的数量
    • 12、分区
    • 13、截断
    • 14、跳过
    • 15、查找与匹配
    • 16、收集
    • 17、全部转大写
    • 18、修改对象属性
    • 19、转换为数组
    • 20、flatMap扁平化处理

1、分组

// 按照sn分组:  List> dataList
Map<String, List<Map<String, Object>>> dataMap = dataList.stream().collect(Collectors.groupingBy(e -> e.get("sn") + ""));	

//按照职员部分分组: List list
Map<String, List<Employee>> collect = list.stream().collect(Collectors.groupingBy(i -> i.getUnitName()));

//多条件分组
Map<String, Map<String,List<Employee>>> collect =list.stream().collect(Collectors.groupingBy(i -> i.getUnitName(),Collectors.groupingBy(i -> i.getWorkType())));

        //按年龄分组,年龄相同的是一组
        Map<Integer, List<Person>> 分组 = list.stream().collect(Collectors.groupingBy(Person::getAge));
 
        //按年龄分组后按工资分组,多级分组
        Map<Integer, Map<String, List<Person>>> 多级分组 = list.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(x -> {
            return x.getSalary() > 3000 ? "高" : "低";
        })));
 
// 分组排序 ,拿已经排好序的过来分组
LinkedHashMap<String, List<AttendanceRuleGroup>> groupingByruleGroupList = ruleGroupList.stream().collect(Collectors.groupingBy(AttendanceRuleGroup::getCategory, LinkedHashMap::new, Collectors.toList()));

// 分组排序,集合没排序,我们自己按我们想要的排序
 LinkedHashMap<String, List<AttendanceRuleGroup>> groupingByruleGroupList = ruleGroupList.stream().sorted(Comparator.comparingLong(AttendanceRuleGroup::getSort).reversed()).collect(Collectors.groupingBy(AttendanceRuleGroup::getCategory, LinkedHashMap::new, Collectors.toList()));

2、过滤

//根据指定sn,过滤出符合的数据: List> deviceDataList
List<Map<String, Object>> tempDeviceDataList = deviceDataList.stream().filter(map -> map.get("sn").toString().equals(sn)).collect(Collectors.toList());

//筛选出工资大于10000的职员
List<Employee> newList = list.stream().filter(item -> {
			return item.getSalary().compareTo(new BigDecimal(10000)) > 0 && !item.getWorkType().equals("项目经理");
		}).collect(Collectors.toList());

3、List map互转

1、list转map

// (k1,k2)->k2 避免键重复 k1-取第一个数据;k2-取最后一条数据
//key和value,都可以根据传入的值返回不同的Map
Map<String, String> deviceMap = hecmEnergyDevicesList.stream().collect(Collectors.toMap(i -> i.getDeviceNum(), j -> j.getDeviceName(), (k1, k2) -> k1));
//
Map<String, Object> map = list.stream()
				.collect(Collectors.toMap(i -> i.getEmpName() + i.getUnitName(), j -> j, (k1, k2) -> k1));

2、map转list

//在.map里面构造数据 return什么数据就转成什么类型的list
List<Employee> collect = map.entrySet().stream().map(item -> {
			Employee employee = new Employee();
			employee.setId(item.getKey());
			employee.setEmpName(item.getValue());
			return employee;
		}).collect(Collectors.toList());

4、求和/极值

//在egyList里面求cols的和
public static BigDecimal getSumBig(List<Map<String,Object>> egyList, String cols){
        BigDecimal consuBig = egyList.stream()
                .filter((Map m)->StringUtils.isNotEmpty(m.get(cols)+"") && !"null".equals(String.valueOf(m.get(cols)))
                        && !"-".equals(String.valueOf(m.get(cols))))
                .map((Map m)->new BigDecimal(m.get(cols)+""))
                .reduce(BigDecimal.ZERO,BigDecimal::add);
        return consuBig;
}

//List list
//Bigdecimal求和/极值: 
BigDecimal sum = list.stream().map(Employee::getSalary).reduce(BigDecimal.ZERO,BigDecimal::add);
BigDecimal max = list.stream().map(Employee::getSalary).reduce(BigDecimal.ZERO,BigDecimal::max);

//基本数据类型求和/极值:
Integer sum = list.stream().mapToInt(Employee::getId).sum();
Long sum = list.stream().mapToLong(Employee::getId).sum();
Double sum = list.stream().mapToDouble(Employee::getId).sum();

OptionalInt optionalMax = list.stream().mapToInt(Employee::getId).max();
optionalMax.getAsInt();

5、求最大/最小值的对象

Optional<Employee> optional = list.stream().collect(Collectors.maxBy(Comparator.comparing(Employee::getId)));
 if (optional.isPresent()) { // 判断是否有值
 		Employee user = optional.get();
 }
return optional.orElse(new Employee());

6、去重

//去重之后进行拼接: List deviceNodeList
Srting deviceNodeStr = deviceNodeList.stream().distinct().collect(Collectors.joining("','"));
//直接去重返回list
// List deviceIdList
 List<String> deviceIdList = deviceIdList.stream().distinct().collect(Collectors.toList());

7、排序

//按照时间排序 1升 -1降
Collections.sort(listFast, (p1, p2) -> {
     return String.valueOf(p1.get("time")).compareTo(p2.get("time") + "");
});

// s1-s2 升序   s2-s1降序
Collections.sort(list,(s1,s2) -> s1.getSalary().compareTo(s2.getSalary()));

//多条件排序: List list, s1-s2 升序   s2-s1降序
list.sort(Comparator.comparing(Employee::getSalary).reversed().thenComparing(Employee::getId).reversed());

8、拼接

//将某个字段,按照某个字符串拼接:  List> deviceMapList 
String sns = deviceMapList.stream()
     	.map((m)->m.get("sn")+"").collect(Collectors.joining(","));
//使用场景很多,在sql里面用于组织in的值.比如:
SELECT sn,time,value FROM electric_real_time WHERE FIND_IN_SET(sn,?)
List<Map<String, Object>> dataList = JdbcUtil.getJdbcTemplate().queryForList(dataSql, sns)

        List<String> strs = Arrays.asList("a","b","cd");
 
        //连接所有内容
        String str = strs.stream().collect(Collectors.joining());
        System.out.println(str);
        //输出:abcd
 
        //连接所有内容,中间加一个逗号隔开
        String str1 = strs.stream().collect(Collectors.joining(","));
        System.out.println(str1);
        //输出:a,b,cd
 
        //连接所有内容,中间加一个逗号隔开,两边加上括号
        String str2 = strs.stream().collect(Collectors.joining(",","(",")"));
        System.out.println(str2);
        //输出:(a,b,cd)

9、统计

//统计:和、数量、最大值、最小值、平均值: List list
IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(Employee::getId));
System.out.println("和:" + collect.getSum());
System.out.println("数量:" + collect.getCount());
System.out.println("最大值:" + collect.getMax());
System.out.println("最小值:" + collect.getMin());
System.out.println("平均值:" + collect.getAverage());

10、平均值

OptionalDouble average = list.stream().mapToInt(Employee::getId).average();
average.getAsDouble();

11、某个值的数量

//List list
Map<BigDecimal, Long> collect = list.stream().collect(Collectors.groupingBy(i -> i.getSalary(),Collectors.counting()));

//List> egyList
long count = egyList.stream()
     .filter((Map m)->StringUtils.isNotEmpty(m.get(cols)+""))
     .map((Map m)->new BigDecimal(m.get(cols)+""))
     .count();

12、分区

//List list
//单层分区
Map<Boolean, List<Employee>> collect = list.stream().collect(Collectors.partitioningBy(i -> i.getId() == 1));

//分区 满足条件的一个区,不满足条件的一个区
        Map<Boolean, List<Person>> collect1 = list.stream().collect(Collectors.partitioningBy(e -> e.getSalary() < 2000));

//多层分区
Map<Boolean, Map<Boolean,List<Employee>>> collect = list.stream().collect(Collectors.partitioningBy(i -> i.getId() == 1,Collectors.partitioningBy(i -> i.getSalary().compareTo(new BigDecimal(20000)) == 0)));

13、截断

        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
 
        //中间操作:不会执行任何操作
        Stream<Integer> stream = list.stream()
                .filter(e -> {
                    System.out.println("过滤 中间操作");
                    return e>3;
                })
                .limit(2);
 
        //终止操作:一次性执行全部内容,惰性求值
        stream.forEach(System.out::println);

14、跳过

        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
 
        //中间操作:不会执行任何操作
        Stream<Integer> stream = list.stream()
                .skip(5);
 
        //终止操作:一次性执行全部内容,惰性求值
        stream.forEach(System.out::println);

15、查找与匹配

        List<Person> list = Arrays.asList(
                new Person(18,3939),
                new Person(38,9999),
                new Person(17,9999),
                new Person(19,9988),
                new Person(38,99)
        );
 
        //是否匹配所有元素 此处返回false
        boolean b = list.stream().allMatch(e -> e.getAge() == 18);
        System.out.println(b);
 
        //至少匹配一个元素,此处返回true
        boolean b1 = list.stream().anyMatch(e -> e.getAge() == 19);
        System.out.println(b1);
 
        //流中是否没有匹配元素,此处返回false
        boolean b2 = list.stream().noneMatch(e -> e.getAge() == 19);
        System.out.println(b2);
 
        //排序后获取第一个元素
        Optional<Person> first = list.stream().sorted((x, y) -> x.getAge().compareTo(y.getAge())).findFirst();
        System.out.println(first);
 
        //获取流中任意一个元素
        list.stream().findAny();
 
        //返回流中元素的总个数
        list.stream().count();
 
        //返回流中最大值 此处根据年龄比较
        Optional<Person> max = list.stream().max((x, y) -> x.getAge().compareTo(y.getAge()));
        System.out.println(max.get());
 
        //返回流中最小值 此处根据年龄比较
        Optional<Person> min = list.stream().min((x, y) -> x.getAge().compareTo(y.getAge()));
        System.out.println(min.get());
 
        //获取最小的年龄
        Optional<Integer> age = list.stream().map(Person::getAge).min(Integer::compareTo);
        System.out.println(age.get());
 
 
        //获取一个并行流,并行流会使用多个线程操作流,stream()获取的是串行流,单个线程操作流
        list.parallelStream();
        
		//查找第一个元素
        Optional<Dish> collect = menu.stream().filter(dish -> dish.getCalories() > 1000).findFrist();
       

16、收集

        //取出所有年龄放到list集合中
        List<Integer> toList = list.stream().map(Person::getAge)
                .collect(Collectors.toList());
 
        //取出所有年龄放到set集合中
        Set<Integer> toSet = list.stream().map(Person::getAge)
                .collect(Collectors.toSet());
 
        //取出所有年龄放到hashSet集合中
        HashSet<Integer> toHashSet = list.stream().map(Person::getAge)
                .collect(Collectors.toCollection(HashSet::new));
 
        //获取集合中元素总和
        Long count = list.stream().collect(Collectors.counting());
 
        //获取年龄平均值
        Double avg = list.stream().collect(Collectors.averagingInt(Person::getAge));
 
        //获取工资总和
        Double sum = list.stream().collect(Collectors.summingDouble(Person::getSalary));
 
        //获取工资最大值的人
        Optional<Person> max = list.stream().collect(Collectors.maxBy((p1, p2) -> Double.compare(p1.getSalary(), p2.getSalary())));
        System.out.println(max.get());
 
        //获取工资最小值的人
        Optional<Person> min = list.stream().collect(Collectors.minBy((p1, p2) -> Double.compare(p1.getSalary(), p2.getSalary())));
        System.out.println(min.get());
 
        //获取元素个数、总和、最小值、平均值、最大值
        DoubleSummaryStatistics collect = list.stream().collect(Collectors.summarizingDouble(Person::getSalary));
        System.out.println(collect);
        //输出结果:DoubleSummaryStatistics{count=5, sum=34024.000000, min=99.000000, average=6804.800000, max=9999.000000}

17、全部转大写

        List<String> list = Arrays.asList("a","vvv","ddd");
 
        //中间操作:不会执行任何操作
        Stream<String> stream = list.stream()
                .map(x -> x.toUpperCase());
 
        //终止操作:一次性执行全部内容,惰性求值
        stream.forEach(System.out::println);

18、修改对象属性

// 过滤集合字段sysOrgCode为a的值的修改为111
List<DepartTreeVO> c = list.stream().filter(a->"a".equals(a.getSysOrgCode())).map(a -> {
	a.setSysOrgCode("111");
	return a;
}).collect(Collectors.toList());

// 给每个对象都填充一样的值
list.stream().forEach(a->{a.setId("11");a.setSysOrgCode("22");});

// 转换为对象
List<String> list = Arrays.asList("111", "222", "333", "444");
List<User> collect = list.stream().map(a -> {
	User user = new User();
	user.setId(a);
	return user;
}).collect(Collectors.toList());

19、转换为数组

// 转换为数组
Integer[] numberArray = numbers.stream().toArray(Integer[]::new);

20、flatMap扁平化处理

// 示例1
List<List<String>> stringLists = Arrays.asList(
    Arrays.asList("a", "b", "c"),
    Arrays.asList("c", "d", "e"),
    Arrays.asList("e", "f", "g")
);
List<String> uniqueCharacters = stringLists.stream()
                                           .flatMap(List::stream)
                                           .distinct()
                                           .collect(Collectors.toList());

System.out.println(uniqueCharacters); // [a, b, c, d, e, f, g]

// 示例2,person.getHobbies()get出来是下面第二个参数,是个集合
List<Person> people = Arrays.asList(
    new Person("John", Arrays.asList("reading", "painting")),
    new Person("Jane", Arrays.asList("swimming", "cooking")),
    new Person("Bob", Arrays.asList("gaming", "hiking"))
);

List<String> allHobbies = people.stream()
                                .flatMap(person -> person.getHobbies().stream())
                                .collect(Collectors.toList());

System.out.println(allHobbies); // [reading, painting, swimming, cooking, gaming, hiking]

。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中
。。。。持续更新添加中

你可能感兴趣的:(java,java,后端)