stream流式编程

stream流式编程

常用的stream三种创建方式

  • 集合 Collection.stream()

  • 静态方法 Stream of

  • 数组 Arrays.stream

//1.集合
Stream<Student> stream = basketballClub.stream();
//2.静态方法
Stream<String> stream2 = Stream.of("a", "b", "c");
//3.数组
String[] arr = {"a","b","c"};
Stream<String> stream3 = Arrays.stream(arr);

Stream的终止操作

  • foreach(Consumer c) 遍历操作
  • collect(Collector) 将流转换为其他的形式
  • max(Comparator) 返回流中最大值
  • min(Comparator) 返回流中最小值
  • count 返回流中元素总数

Collectors 具体方法

  • toList List 把流中的元素收集到List
  • toSet Set 把流中的元素收集到Set
  • toCollection Coolection 把流中元素收集到Collection中
  • groupingBy Map<K,List> 根据K属性对流进行分组
  • partitioningBy Map<boolean, List> 根据boolean值进行分组

常用方法

filter

/**
     * filter - 筛选
     */
public static void filter(List<Student> studentList){
    List<Student> collect = studentList.stream().filter(student -> student.getAge() > 2).collect(Collectors.toList());
    collect.forEach(e-> System.out.println(e));

}
public static void filter02(List<Student> studentList){
    List<Student> zishu = studentList.stream().filter(student -> student.getName().equals("zishu")).collect(Collectors.toList());
    zishu.forEach(e-> System.out.println(e));
}

map

map(Function f) 接收流中元素,并且将其映射成为新元素,例如从student对象中取name属性

 /**
     * 将两个字段组成map
     * 其中key必须是唯一的
     */
    public static void toMap(List<Student> studentList){
        Map<Integer, String> collect = studentList.stream().collect(Collectors.toMap(Student::getId, Student::getName));
        collect.forEach((key,value)->{
            System.out.println("key==="+key);
            System.out.println("value==="+value);
        });
    }
    /**
      * 将某个字段提取生成一个新的list
      *
     **/
    List<Object> newList = objectList.stream().map(Object::getVar).collect(Collectors.toList());

groupBy

/**
     * groupBy - 分组 - 根据一个字段进行分组
     */
public static void groupBy(List<Student> studentList){
    Map<Integer, List<Student>> collect = studentList.stream().collect(Collectors.groupingBy(Student::getId));
    collect.forEach((key,value)->{
        System.out.println("key==="+key);
        System.out.println("value==="+value);
    });
}
   /**
     * groupBy - 分组 - 根据多个字段进行分组
     */
public static void groupBy02(List<Student> studentList){
    Map<String, List<Student>> collect = studentList.stream().collect(Collectors.groupingBy(student ->
                                                                                            student.getId() +","+ student.getName()
                                                                                           ));
    collect.forEach((key,value)->{
        System.out.println("key==="+key);
        System.out.println("value==="+value);
    });
}

求和

list.stream().mapToDouble(User::getHeight).sum()//和
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值
Double示例:

public class HelloWorld {
    private static final DecimalFormat df = new DecimalFormat("0.00");//保留两位小数点
    public static void main(String[] args) {
        Random random = new Random();
        List<User> list = new ArrayList<>();
        for(int i=1;i<=5;i++) {
            double weight = random.nextDouble() * 100 + 100;//随机身高:100-200
            User u = new User(i, "用户-" + i, weight);
            list.add(u);
        }
        System.out.println("用户:" + list);
        double sum = list.stream().mapToDouble(User::getHeight).sum();
        System.out.println("身高 总和:" + df.format(sum));
        double max = list.stream().mapToDouble(User::getHeight).max().getAsDouble();
        System.out.println("身高 最大:" + df.format(max));
        double min = list.stream().mapToDouble(User::getHeight).min().getAsDouble();
        System.out.println("身高 最小:" + df.format(min));
        double average = list.stream().mapToDouble(User::getHeight).average().getAsDouble();
        System.out.println("身高 平均:" + df.format(average));

    }
BigDecimal示例:

public class HelloWorld {
    private static final DecimalFormat df = new DecimalFormat("0.00");//保留两位小数点
    public static void main(String[] args) {
        Random random = new Random();
        List<User> list = new ArrayList<>();
        for(int i=1;i<=5;i++) {
            double weight = random.nextDouble() * 100 + 100;//随机身高:100-200
            list.add(new User(i, new BigDecimal(weight).setScale(BigDecimal.ROUND_HALF_UP, 2)));
        }
        System.out.println("list:" + list);
        BigDecimal add = list.stream().map(User::getHeight).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("身高 总和:" + df.format(add));
        Optional<User> max = list.stream().max((u1, u2) -> u1.getHeight().compareTo(u2.getHeight()));
        System.out.println("身高 最大:" + df.format(max.get().getHeight()));
        Optional<User> min = list.stream().min((u1, u2) -> u1.getHeight().compareTo(u2.getHeight()));
        System.out.println("身高 最小:" + df.format(min.get().getHeight()));

    }

交集,并集,差集

交集(listA ∩ ListB):
List<Person> listC = listA.stream().filter(item -> listB.contains(item)).collect(Collectors.toList());
listC中的元素有:属性name值为 aa, bb, cc 的对象。

并集(listA ∪ listB):
//先合体
listA.addAll(listB);
//再去重
List<Person> listC = listA.stream().distinct().collect(Collectors.toList());
listC中的元素有:属性name值为 aa, bb, cc ,dd的对象。

差集(listA - listB):
List<Person> listC = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());

flatMap

flatMap(Function f) 将所有流中的元素并到一起连接成一个流

/**
     * 将三个集合组合,然后进行筛选
     */
    public static void collectThree(List<Student> list1,List<Student> list2,List<Student> list3){
        Stream<List<Student>> listStream = Stream.of(list1, list2, list3);
        List<Student> collect = listStream.flatMap(e -> e.stream().filter(student -> student.getAge() > 50)).collect(Collectors.toList());
        collect.forEach(e-> System.out.println(e));
    }

peek

peek(Consumer c) 获取流中元素,操作流中元素,与foreach不同的是不会截断流,可继续操作流

/**
 * peek
 */
    public static void peek(List<Student> list){
        list.stream().peek(student -> student.setName(student.getName()+"88888"))
                .collect(Collectors.toList())
                .forEach(e-> System.out.println(e));

    }

distinct

distinct() 通过流所生成元素的equals和hashCode去重

/**
 * 去重
 */
    public static void distinct(List<String> list){
        List<String> collect = list.stream().distinct().collect(Collectors.toList());
        collect.forEach(e-> System.out.println(e));
    }

limit

limit(long val) 截断流,取流中前val个元素

/**
 * 截取
 */
    public static void limit(List<String> list){
        List<String> collect = list.stream().limit(2).collect(Collectors.toList());
        collect.forEach(e-> System.out.println(e));
    }

sorted

sorted(Comparator) 产生一个新流,按照比较器规则排序

/**
 * 排序
 *             从小到大
 *           list.sort(((o1, o2) -> o1-o2));
 *             从大到小
 *           list.sort(((o1, o2) -> o2-o1));
 */
    public static void sort(List<Integer> list){
        List<Integer> collect = list.stream().sorted(((o1, o2) -> o2 - o1)).collect(Collectors.toList());
        collect.forEach(e-> System.out.println(e));

    }



// 升序
employDOList.stream().sorted(Comparator.comparing(EmployDO::getAge)).collect(Collectors.toList())
    .forEach(s -> System.out.print(s.getName() + "  "));
System.out.println("      ");
// 降序
employDOList.stream().sorted(Comparator.comparing(EmployDO::getAge).reversed())
    .forEach(s -> System.out.print(s.getName() + "  "));

    

match匹配

  • boolean allMatch(Predicate) 都符合
  • boolean anyMatch(Predicate) 任一元素符合
  • boolean noneMatch(Predicate) 都不符合

find寻找元素

  • findFirst——返回第一个元素
  • findAny——返回当前流中的任意元素
Optional<Student> first = basketballClub.stream().findFirst();
if (first.isPresent()) {
    Student student = first.get();
    System.out.println(student);
}

Optional<Student> any = basketballClub.stream().findAny();
if (any.isPresent()) {
    Student student2 = any.get();
    System.out.println(student2);
}
Optional<Student> any1 = basketballClub.stream().parallel().findAny();
System.out.println(any1);

计数和极值

  • count——返回流中元素的总个数
  • max——返回流中最大值
  • min——返回流中最小值
long count = basketballClub.stream().count();
Optional<Student> max = basketballClub.stream().max(Comparator.comparing(Student::getAge));
if (max.isPresent()) {
    Student student = max.get();
}
Optional<Student> min = basketballClub.stream().min(Comparator.comparingInt(Student::getAge));
if (min.isPresent()) {
    Student student = min.get();
}
~~~java
Optional<Student> max = basketballClub.stream().max(Comparator.comparing(Student::getAge));
if (max.isPresent()) {
    Student student = max.get();
}
Optional<Student> min = basketballClub.stream().min(Comparator.comparingInt(Student::getAge));
if (min.isPresent()) {
    Student student = min.get();
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值