java8的Stream对集合操作

(1)~(9) 、(11)~(12)引用:
https://juejin.im/post/5d5e2616f265da03b638b28a
作者:坚持就是胜利
(10)引用:
https://blog.csdn.net/SUDDEV/article/details/79375211
作者:SUDDEV

  • (1) filter 的使用
  • (2) map 的使用
  • (3)集合去重(基本类型)
  • (4) 集合去重(引用对象)
  • (5)集合排序(默认排序)
  • (6)集合排序(指定排序规则)
  • (7) limit(限制返回个数)
  • (8) skip(删除元素)
  • (9) reduce(聚合)
  • (10) reduce : 实现 BigDecimal 的累加
  • (11) min(求最小值) :求集合中元素的最小值
  • (12) anyMatch/allMatch/noneMatch(匹配)
package com.java8_stream;

import java.util.Objects;

public class Student {
    private Long id;
    private String name;
    private int age;
    private String address;

    public Student() {}

    public Student(Long id, String name, int age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(id, student.id) &&
                Objects.equals(name, student.name) &&
                Objects.equals(address, student.address);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age, address);
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
}
package com.java8_stream;

import java.math.BigDecimal;

public class User {
    private long id;
    private BigDecimal money;

    public User(long id, BigDecimal money) {
        this.id = id;
        this.money = money;
    }

    public long getId() {
        return id;
    }

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

    public BigDecimal getMoney() {
        return money;
    }

    public void setMoney(BigDecimal money) {
        this.money = money;
    }
}
package com.java8_stream;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class streamLearnTest {
    public static void main(String [] args) {

        Student s1 = new Student(1L, "肖战", 15, "浙江");
        Student s2 = new Student(2L, "王一博", 15, "湖北");
        Student s3 = new Student(3L, "杨紫", 17, "北京");
        Student s4 = new Student(4L, "李现", 17, "浙江");
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);

        // (1) filter 的使用
        List<Student> streamStudents = testFilter(students);
        streamStudents.forEach(System.out::println);

        //(2) map 的使用
        System.out.println("================================");
        testMap(students);

        //(3)集合去重(基本类型)
        System.out.println("================================");
        testDistinct1();

        //(4) 集合去重(引用对象)
        /**
         * 两个重复的“肖战”同学进行了去重,这不仅因为使用了distinct()方法,
         * 而且因为Student对象重写了equals和hashCode()方法,否则去重是无效的。
         * */
        System.out.println("================================");
        testDistinct2();

        //(5)集合排序(默认排序)
        System.out.println("================================");
        testSort1();

        //(6)集合排序(指定排序规则)
        System.out.println("================================");
        testSort2();

        //(7) limit(限制返回个数)
        System.out.println("================================");
        testLimit();

        //(8) skip(删除元素)
        System.out.println("================================");
        testSkip();

        //(9) reduce(聚合)
        System.out.println("================================");
        testReduce();

        //(10) reduce : 实现 BigDecimal 的累加
        System.out.println("================================");
        testReduceAdd();

        //(11) min(求最小值) :求集合中元素的最小值
        System.out.println("================================");
        testMin();

        //(12) anyMatch/allMatch/noneMatch(匹配)
        System.out.println("================================");
        testMatch();
    }
}
/**
* (1) filter 的使用 : 集合的筛选
*/
private static List<Student> testFilter(List<Student> students) {
   //筛选年龄大于15岁的学生
   // return students.stream().filter(s -> s.getAge()>15).collect(Collectors.toList());
   //筛选住在浙江省的学生
   return students.stream().filter(
         s ->"浙江".equals(s.getAddress())).collect(Collectors.toList());
}
/**
* (2) map 的使用 : 集合转换 :map就是将对应的元素按照给定的方法进行转换。
*/
private static void testMap(List<Student> students) {
   //在地址前面加上部分信息,只获取地址输出
   List<String> addresses = students.stream().map(s ->"住址:"+s.getAddress()).collect(Collectors.toList());
   addresses.forEach(a ->System.out.println(a));  //  <==>等价于:  addresses.forEach(System.out::println);
}
/**
* (3) 集合去重(基本类型)
*/
private static void testDistinct1() {
   //简单字符串的去重
   List<String> list = Arrays.asList("333","222","111","111","222");
   list.stream().distinct().forEach(s -> System.out.println(s));
}
/**
* (4) 集合去重(引用对象)
*/
private static void testDistinct2() {
   //引用对象的去重,引用对象要实现hashCode和equal方法,否则去重无效
   Student s1 = new Student(1L, "肖战", 15, "浙江");
   Student s2 = new Student(2L, "王一博", 15, "湖北");
   Student s3 = new Student(3L, "杨紫", 17, "北京");
   Student s4 = new Student(4L, "李现", 17, "浙江");
   Student s5 = new Student(1L, "肖战", 15, "浙江");
   List<Student> students = new ArrayList<>();
   students.add(s1);
   students.add(s2);
   students.add(s3);
   students.add(s4);
   students.add(s5);
   students.stream().distinct().forEach(System.out::println);
}
/**
* (5)集合排序(默认排序)
*/
private static void testSort1() {
   List<String> list = Arrays.asList("333","222","111");
   list.stream().sorted().forEach(s -> System.out.println(s));
}
/**
 * (6)集合排序(指定排序规则)
 */
private static void testSort2() {
   Student s1 = new Student(1L, "肖战", 19, "浙江");
   Student s2 = new Student(2L, "王一博", 15, "湖北");
   Student s3 = new Student(3L, "杨紫", 18, "北京");
   Student s4 = new Student(4L, "李现", 17, "浙江");
   List<Student> students = new ArrayList<>();
   students.add(s1);
   students.add(s2);
   students.add(s3);
   students.add(s4);
   //按照学生的id进行降序排序
   students.stream()
      .sorted((stu1,stu2) ->Long.compare(stu2.getId(), stu1.getId()))
      .forEach(student -> System.out.println(student));

}
/**
 * (7) limit(限制返回个数)
 */
private static void testLimit() {
   List<String> list = Arrays.asList("333","222","111");
   list.stream().limit(2).forEach(System.out::println);
}
/**
* (8) skip(删除元素)
*    在丢弃流的前n个元素后,返回由该流的其余元素组成的流。
* 如果此流包含的元素少于n个,则将返回空流。
*/
private static void testSkip() {
   List<String> list = Arrays.asList("555","444","333","222","111");
   list.stream().skip(4).forEach(s -> System.out.println(s));
}
/**
 * (9) reduce(聚合) : 集合reduce,将集合中每个元素聚合成一条数据
 */
private static void testReduce() {
   List<String> list = Arrays.asList("欢","迎","你");
   String appendStr = list.stream().reduce("北京",(a,b)->a+b);
   System.out.println(appendStr);
}
/**
* (10) reduce : 实现 BigDecimal 的累加
*/
private static void testReduceAdd(){
   // 准备数据
   List<User> userList = new ArrayList<User>();
   for (int i = 0; i < 100; i++) {
   User user = new User(i,new BigDecimal(i+"."+i));
   userList.add(user);
   }
   // java 8 stream version
   BigDecimal result = userList.stream()
                        // 将user对象的mongey取出来map为Bigdecimal
                        .map(User::getMoney)
                        // 使用reduce聚合函数,实现累加器
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
   //可用:BigDecimal result2 =  userList.stream().map(user -> user.getMoney()).reduce(BigDecimal.ZERO,BigDecimal::add);
   System.out.println("result = "+result);

}
/**
* (11)
* ① min(求最小值) :求集合中元素的最小值
* ② max 反之
*/
private static void testMin() {
   Student s1 = new Student(1L, "肖战", 18, "浙江");
   Student s2 = new Student(2L, "王一博", 15, "湖北");
   Student s3 = new Student(3L, "杨紫", 17, "北京");
   Student s4 = new Student(4L, "李现", 17, "浙江");
   List<Student> students = new ArrayList<>();
   students.add(s1);
   students.add(s2);
   students.add(s3);
   students.add(s4);
   Student min = students.stream().min((stu1,stu2) ->Integer.compare(stu1.getAge(),stu2.getAge())).get();
   System.out.println(min.toString());
   System.out.println("----------------------------------");
   Student max = students.stream().max((stu1,stu2) ->Integer.compare(stu1.getAge(),stu2.getAge())).get();
   System.out.println(max.toString());
}
/**
* (12) anyMatch/allMatch/noneMatch(匹配)
*
*/
private static void testMatch() {
   Student s1 = new Student(1L, "肖战", 15, "浙江");
   Student s2 = new Student(2L, "王一博", 15, "湖北");
   Student s3 = new Student(3L, "杨紫", 17, "北京");
   Student s4 = new Student(4L, "李现", 17, "浙江");
   List<Student> students = new ArrayList<>();
   students.add(s1);
   students.add(s2);
   students.add(s3);
   students.add(s4);
   Boolean anyMatch = students.stream().anyMatch(s->"湖北".equals(s.getAddress()));

   if (anyMatch) {
   System.out.println("有湖北人");
   }
   Boolean allMatch = students.stream().allMatch(s->s.getAge()>=15);
   if (allMatch) {
   System.out.println("所有学生都满15周岁");
   }
   Boolean noneMatch = students.stream().noneMatch(s->"杨洋".equals(s.getName()));
   if (noneMatch) {
   System.out.println("没有叫杨洋的同学");
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值