Java8新特性stream

JAVA8新特性stream

排序、规约、过滤、分组、分区、字符串连接、Optional

实体类

package com.test.demo.model;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Data
@Setter
@Getter
@ToString
public class TestUser{
     

    private Integer id;

    private Integer age;

    private String name;

    public TestUser(Integer id, Integer age, String name) {
     
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public Integer getId() {
     
        return id;
    }

    public void setId(Integer id) {
     
        this.id = id;
    }

    public Integer getAge() {
     
        return age;
    }

    public void setAge(Integer age) {
     
        this.age = age;
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

}

测试类

package com.test.demo;

import com.test.demo.model.TestUser;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.awt.geom.Ellipse2D;
import java.util.*;
import java.util.stream.Collectors;

@SpringBootTest
class DemoApplicationTests {
     

    List<TestUser> userList = Arrays.asList(
            new TestUser(2, 100, "aaa"),
            new TestUser(1, 30, "bbb"),
            new TestUser(4, 40, "aaa"),
            new TestUser(9, 44, "eee"),
            new TestUser(5, 44, "ccc"),
            new TestUser(1, 30, "qqq"),
            new TestUser(2, 30, "wwww")
    );


    // 排序
    @Test
    public void test() {
     
        // TODO 如果年龄一样按姓名排序,如果年龄不一样按年龄排序  倒排-user1.getAge().compareTo(user2.getAge());
        userList.stream()
                .sorted((user1, user2) -> {
     
                    if (user1.getAge().equals(user2.getAge())) {
     
                        return user1.getName().compareTo(user2.getName());
                    } else {
     
                        return user1.getAge().compareTo(user2.getAge());
                    }
                }).forEach(System.out::println);
    }


    /**
     * allMatch     匹配全部
     * anyMatch     至少匹配一个
     * noneMatch    检查否没有匹配的所有元素,如果都不匹配为true
     * findFirst    取第一个数据
     * orElse       else 否则
     * findAny      返回任意一个元素
     * count        获取总数
     * max          取出最大元素
     * min          获取最小
     **/

    @Test
    public void test2() {
     
        //匹配全部
        boolean b1 = userList.stream()
                .allMatch((testUser) -> testUser.getAge().equals(40));
        System.out.println(b1);//false

        //至少匹配一个
        boolean b2 = userList.stream()
                .anyMatch((testUser) -> testUser.getAge().equals(40));
        System.out.println(b2);//true


        //检查否没有匹配的所有元素,如果都不匹配为true
        boolean b3 = userList.stream()
                .noneMatch((testUser) -> testUser.getAge().equals(40));
        System.out.println(b3);//false


        //根据年龄倒排,然后取第一个,如果userList为空的话,执行orElse
        TestUser testUser = userList.stream().sorted((user1, user2) -> -Integer.compare(user1.getAge(), user2.getAge())).findFirst().orElse(new TestUser(1, 1, "1"));
        System.out.println(testUser);


        //串行执行返回任意一个id为1的元素
        TestUser testUser2 = userList.stream().filter(testUser1 -> testUser1.getId().equals(1)).findAny().get();
        System.out.println("串行执行返回任意一个id为1的元素 :" + testUser2);

        //并行执行返回任意一个id为1的元素
        TestUser testUser3 = userList.parallelStream().filter(testUser1 -> testUser1.getId().equals(1)).findAny().get();
        System.out.println("并行执行返回任意一个id为1的元素 :" + testUser3);

        //获取总数
        long count = userList.stream().count();
        System.out.println("获取总数:" + count);

        //取出ID最大的user,如果有相同的返回第一个元素
        Optional<TestUser> max = userList.stream().max((user1, user2) -> Integer.compare(user1.getId(), user2.getId()));
        System.out.println("获取ID最大的User " + max.get());

        //取出ID最大的值
        Integer max1 = userList.stream().map(TestUser::getId).max(Integer::compareTo).get();
        System.out.println("获取ID最大值:" + max1);

        //取出ID最小的user,如果有相同的返回第一个元素
        Optional<TestUser> min = userList.stream().min((user1, user2) -> Integer.compare(user1.getId(), user2.getId()));
        System.out.println("获取ID最小的User " + min.get());

        //取出ID最小的值
        Integer min1 = userList.stream().map(TestUser::getId).min(Integer::compareTo).get();
        System.out.println("获取ID最大值:" + min1);

    }


    //归约
    @Test
    public void test3() {
     
        //归约将流中元素反复结合起来,得到一个值,累加
        //第一次的0他取的是数组中的第一个值1作为x然后+y y也是从0开始那就是 1+1
        //第二次x就是1了,那么y就是2了,然后继续操作以此类推的方式去求
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer sum = integerList.stream()
                .reduce(0, (x, y) -> x + y);
        System.out.println("总数:" + sum);


        //求出年龄的规约总数
        Integer ageSum = userList.stream()
                .map(TestUser::getAge)
                .reduce(Integer::sum).get();
        System.out.println("年龄规约总数:" + ageSum);
    }

    /**
     * 收集
     * 

* collect 将流转换为其他形式,接收一个 Collector 接口的实现,用于 Stream 中元素做汇总 * toList 返回List集合,也可以是set等 * averagingInt 获取平均值 * summingInt 获取年龄总和 * summarizingInt 获取所有聚合值 count sum min average max * maxBy 获取最大元素 * minBy 获取最小元素 **/ @Test public void test4() { //获取名称List集合 List<String> nameList = userList.stream().map(TestUser::getName).collect(Collectors.toList()); System.out.println("所有名称List集合:" + nameList); //获取名称Set集合去重 Set<String> nameSet = userList.stream().map(TestUser::getName).collect(Collectors.toSet()); System.out.println("所有名称Set集合:" + nameSet); //获取名称HashSet HashSet<String> nameHashSet = userList.stream().map(TestUser::getName).collect(Collectors.toCollection(HashSet::new)); System.out.println("所有名称HashSet集合:" + nameHashSet); //获取年龄的平均值 Double avg = userList.stream().collect(Collectors.averagingInt(TestUser::getAge)); System.out.println("获取年龄的平均值:" + avg); //获取年龄总和 Integer sum = userList.stream().collect(Collectors.summingInt(TestUser::getAge)); System.out.println("获取年龄总和:" + sum); //获取所有聚合值 IntSummaryStatistics collect = userList.stream().collect(Collectors.summarizingInt(TestUser::getAge)); System.out.println("获取所有聚合值:" + collect); //获取ID最大的元素 Optional<TestUser> maxUser = userList.stream().collect(Collectors.maxBy((user1, user2) -> Integer.compare(user1.getId(), user2.getId()))); System.out.println("获取最大ID元素:" + maxUser.get()); //获取ID最小的元素 Optional<TestUser> minUser = userList.stream().collect(Collectors.minBy((user1, user2) -> Integer.compare(user1.getId(), user2.getId()))); System.out.println("获取最小ID元素:" + minUser.get()); } /** * 分组 **/ @Test public void test5() { //按名称进行分组,Map key就是字段值 list分组数据 Map<String, List<TestUser>> groupingByName = userList.stream().collect(Collectors.groupingBy(TestUser::getName)); System.out.println("按用户名称进行分组" + groupingByName); //按用户名称进行分组{qqq=[TestUser(id=1, age=30, name=qqq)], aaa=[TestUser(id=2, age=100, name=aaa), TestUser(id=4, age=40, name=aaa)], ccc=[TestUser(id=5, age=44, name=ccc)], bbb=[TestUser(id=1, age=30, name=bbb)], eee=[TestUser(id=9, age=44, name=eee)], wwww=[TestUser(id=2, age=30, name=wwww)]} //多級分組,先进行名称分组,然后进行年龄分组 Map<String, Map<Object, List<TestUser>>> collect = userList.stream().collect(Collectors.groupingBy(TestUser::getName, Collectors.groupingBy((user) -> { if (user.getAge() == 100) { return "最大"; } else if (user.getAge() == 40) { return "一般"; } else { return ""; } }))); System.out.println("多级分组数据:" + collect); //多级分组数据:{qqq={=[TestUser(id=1, age=30, name=qqq)]}, aaa={一般=[TestUser(id=4, age=40, name=aaa)], 最大=[TestUser(id=2, age=100, name=aaa)]}, ccc={=[TestUser(id=5, age=44, name=ccc)]}, bbb={=[TestUser(id=1, age=30, name=bbb)]}, eee={=[TestUser(id=9, age=44, name=eee)]}, wwww={=[TestUser(id=2, age=30, name=wwww)]}} } /** * @Description //TODO 分区 **/ @Test void contextLoads() { Map<Boolean, List<TestUser>> collect = userList.stream().collect(Collectors.partitioningBy((e) -> e.getAge() > 40)); System.out.println("分区数据:" + collect); //{false=[TestUser(id=1, age=30, name=bbb), TestUser(id=4, age=40, name=aaa), TestUser(id=1, age=30, name=qqq), TestUser(id=2, age=30, name=wwww)], // true=[TestUser(id=2, age=100, name=aaa), TestUser(id=9, age=44, name=eee), TestUser(id=5, age=44, name=ccc)]} } /** * @Description //TODO 字符串连接 **/ @Test void test7(){ String str = userList.stream().map(TestUser::getName).collect(Collectors.joining()); System.out.println("连接字符串:"+str); //aaabbbaaaeeecccqqqwwww String str1 = userList.stream().map(TestUser::getName).collect(Collectors.joining(",")); System.out.println("逗号连接字符串:"+str1); //aaa,bbb,aaa,eee,ccc,qqq,wwww } /** * @Description //TODO Optional **/ @Test void optionnal1(){ //采用Optional创建对象 Optional<TestUser> testUser = Optional.of(new TestUser(2, 100, "aaa")); TestUser testUser1 = testUser.get(); System.out.println("采用Optional创建对象:"+testUser1); //java.util.NoSuchElementException: No value present ,创建对象如果为null可快速定位异常 /*Optional o = Optional.ofNullable(null); System.out.println(o.get());*/ //构建空的 /*Optional empty = Optional.empty(); System.out.println(empty.get());*/ Optional<TestUser> o1 = Optional.ofNullable(new TestUser(2, 100, "aaa")); if(o1.isPresent()){ //如果存在值,才会进入 System.out.println("如果存在值,才会进入:"+o1); } TestUser aaa = o1.orElse(new TestUser(222222, 222, "2222222222222")); System.out.println("否側就是上面的对象没值在这里设置默认值"+aaa); } }

你可能感兴趣的:(java)