• 学习java第22天


    1.流

    得到流    Stream<T>stream = collection.stream();

    对于数组 : Arrays.sstream(ary)

    对于collection :  用list.stream()

    import java.util.*;
    class streamList {
       public static void main(String... args) {
     Collection<Person> people = Arrays.asList(
          new Person("Ted", 18, 88),
          new Person("Charlotte", 18, 88),
          new Person("Michael", 18, 99),
          new Person("Matthew", 19, 84),
          new Person("Matthew", 21, 84)
       );
     Object result =
     people.parallelStream()
      .filter( p -> p.age<20 )
      .sorted( (p1,p2)->p1.age-p2.age)
      .sorted( Person::better)
      .sorted( Comparator.comparing( Person::getName ) )
      .limit(5)
      .mapToDouble( p -> p.score )
      .average();
        System.out.println(result);
      }
    }
    class Person
    {
     public String name;
     public int age;
     public double score;
     public Person(String n, int a, double s) {
      name = n; age = a; score = s;
     }
     public String getName(){ return name;}
     @Override
     public String toString() {
      return String.format("%s[%d](%f)", name,age,score);
     }
     public static int better(Person p1, Person p2) {
      return (int)(p2.score - p1.score);
     }
    }
     
    对于map :  没有流,有相似方法
    map.merge

    *数组进行流化

    Arrays.stream(a)

              .filter(i -> i < 20)

              .map(i -> i*i)

              .max();

    import java.util.*;
    class streamArray
    {
     public static void main(String[] args)
     {
      int [] a = new int[100];
      for(int i=0; i<a.length; i++)
       a[i] = (int)(Math.random()*100);
      
      OptionalInt result=
       Arrays.stream(a).parallel()
       .filter( i -> i>20 )
       .map( i -> i*i )
       .sorted()
       .distinct()
       .limit(10)
       .max();
      System.out.println(
       result.isPresent()? "最大值为"+result.getAsInt(): "无值");
     }
    }
    2.并行的流式操作
    import java.util.*;
    class UseParallelStream
    {
     public static void main(String[] args)
     {
      List<Integer> a = Arrays.asList(1,2,5,7,3);
      System.out.println(
      a.parallelStream()
       .mapToInt(i->(int)i)
       .filter( i -> i>2 )
       .map( i -> i*i )
       .sorted()
       .distinct()
       .limit(10)
       .max()
      );
     }
    }
     
    明天学习内容:
    输入输出流
     
     
     
  • 相关阅读:
    【C/C++】例题5-4 反片语/算法竞赛入门经典/C++与STL入门/映射:map
    【VSCode】如何打开全屏模式/退出全屏模式
    【合同】电子科技大学/外协合同/采购合同
    新的开始
    ubuntu server 1604 搭建FTP服务器
    vim的查找功能
    Ubuntu改坏sudoers后无法使用sudo的解决办法
    ubuntu server 1604 配置网络信息
    ubuntu server 1604 关机和重启
    ubuntu server 1604 设置笔记本盒盖 不操作
  • 原文地址:https://www.cnblogs.com/SirNie/p/13386377.html
Copyright © 2020-2023  润新知