zoukankan      html  css  js  c++  java
  • 学习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()
      );
     }
    }
     
    明天学习内容:
    输入输出流
     
     
     
  • 相关阅读:
    editable : false与 readonly 的区别
    Ubuntu环境下使用Jupyter Notebook查找桌面.csv文档的方法
    实验01——java模拟银行ATM系统
    Wannafly挑战赛26 御坂网络
    Wannafly挑战赛29 御坂美琴(递归,模拟)
    牛客练习赛31 龙魂合一萨坎与晶石
    牛客练习赛31
    Codeforces Round #520 (Div. 2)A. A Prank
    (花里胡哨)New Game!(牛客国庆集训派对Day1)
    Educational Codeforces Round 54 (Rated for Div. 2)A. Minimizing the String(签到题)
  • 原文地址:https://www.cnblogs.com/SirNie/p/13386377.html
Copyright © 2011-2022 走看看