java8 stream api 随记

java8 stream api 随记

实体类

public class User {

    private  String name;
    private  Integer id;
    private Integer age=18;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        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;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                '}';
    }

    static class Leader
    {
        private String name;
        private double salary;

        public String getName() {
            return name;
        }

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

        public double getSalary() {
            return salary;
        }

        public void setSalary(double salary) {
            this.salary = salary;
        }

        @Override
        public String toString() {
            return "Leader{" +
                    "name='" + name + '\'' +
                    ", salary=" + salary +
                    '}';
        }
    }
    
    
}

测试类

public static void main(String[] args) {
     List<User> list = Arrays.asList(
            new User(1, "Alex", 1000),
            new User(2, "Michael", 2000),
            new User(3, "Jack", 1500),
            new User(4, "Owen", 1500),
            new User(5, "Denny", 2000));
            }

map()

  List<User.Leader> leaders = list.stream().filter(
            employee -> employee.getAge() > 1000).map(employee -> {
        User.Leader leader = new User.Leader();
        leader.setName(employee.getName());
        leader.setSalary(employee.getAge());
        return leader;
    }).peek(leader->System.out.println(leader.getName()+"=="+leader.getSalary()))
    .collect(Collectors.toList());

java8 stream api 随记

findAny()和findFirst()

  //查找任意
    System.out.println(list.stream().findAny().get());
    //第一个元素
    System.out.println(list.stream().findFirst().get());

java8 stream api 随记

filter()

    System.out.println(list.stream().filter(user ->user.getAge() >= 1500&&user.getId()>3)
    .collect(Collectors.toList()));

java8 stream api 随记

peek()

  list.stream().peek(user -> {
            if (user.getId() == 1)
                user.setName("修改后的名称");

        }).collect(Collectors.toList()).forEach(System.out::println);

java8 stream api 随记

allMatch()和anyMatch()

   //所有匹配成功,返还true
    System.out.println(list.stream().allMatch(user -> user.getName().startsWith("A")));
    //任意匹配成功及返还true
    System.out.println(list.stream().anyMatch(user -> user.getName().startsWith("A")));

java8 stream api 随记

distinct()

直接使用达不到效果

直接使用达不到效果,一般会根据需求重写对象的hashCode()和equals()方法
list.stream().distinct().forEach(System.out::println);
java8 stream api 随记

将需要去重的部分单独独立,如将age去重

将需要去重的部分单独独立,如将age去重
list.stream().mapToInt(User::getAge).distinct().forEach(System.out::println);
java8 stream api 随记

自定义去重方法

static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
list.stream().filter(distinctByKey(user -> user.getAge()))
.forEach(user -> System.out.println(user.getName()+user.getAge()));

java8 stream api 随记
或者将list改为

 List<User> list = Arrays.asList(
                new User(1, "Alex", 1000),
                new User(1, "Michael", 2000),
                new User(1, "Jack", 1500),
                new User(4, "Owen", 1500),
                new User(5, "Denny", 2000));
list.stream().filter(distinctByKey(user -> user.getId())).forEach(System.out::println);
}

java8 stream api 随记

count()

//过滤再计数
System.out.println(list.stream().filter(user -> user.getId()==1).count());
java8 stream api 随记

limit()

//取2个元素
list.stream().limit(2).forEach(System.out::println);
java8 stream api 随记

max()和min()

 //最大值根据id
    System.out.println(list.stream().max(Comparator.comparing(User::getId)).get());
    //最小值根据id
    System.out.println(list.stream().min(Comparator.comparing(User::getId)).get());

java8 stream api 随记

skip()

//删除3个元素,从前往后
list.stream().skip(3).forEach(System.out::println);

java8 stream api 随记

noneMatch()

//id=0的匹配不到
        System.out.println(list.stream().noneMatch(user -> user.getId() == 0));
//id=1的匹配不到
        System.out.println(list.stream().noneMatch(user -> user.getId() == 1));

java8 stream api 随记

forEachOrdered()

list.stream().forEachOrdered(user -> System.out.println(user.getName()));
java8 stream api 随记

toArray()

System.out.println(list.stream().toArray().length);

java8 stream api 随记

sorted()

升序

//根据age排序
  list.stream().sorted(Comparator.comparing(User::getAge)).forEach(System.out::println);

java8 stream api 随记

降序

//先升序在降序
list.stream().sorted(Comparator.comparing(User::getAge).reversed()).forEach(System.out::println);

java8 stream api 随记

//直接降序
list.stream().sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder()))
.forEach(System.out::println);

java8 stream api 随记

多属性升序

   //在age升序基础上,id也升序
      list.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getId)).forEach(System.out::println);

java8 stream api 随记

  // 在age升序基础上,id降序
      list.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getId,Comparator.reverseOrder())).forEach(System.out::println);

java8 stream api 随记

多属性降序

  // 在age降序基础上,id降序
      list.stream().sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder()).thenComparing(User::getId,Comparator.reverseOrder())).forEach(System.out::println);

java8 stream api 随记

//在age降序基础上,id升序  list.stream().sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder()).thenComparing(User::getId)).forEach(System.out::println);

java8 stream api 随记
所写均为个人理解,理解有误,欢迎指出,谢谢!

上一篇:Velocity官方指南-Velocity是如何工作的


下一篇:Java8-Stream:2万字20个实例,玩转集合的筛选,java面试题全集骆昊