1. 程式人生 > >java8_02_stream(一)建立流和中間操作

java8_02_stream(一)建立流和中間操作

Stream 主要分為三部分 1. 建立流 2.中間操作 3.終止操作

一、建立流的四種方法

  1. Collection系列集合的stream() parallelStream() 方法

    Stream stringStream = list.stream();

  2. Arrays.stream(T[] t)
    Stream studentStream = Arrays.stream(students);
  3. Stream.of(T… values)
    Stream stringStream = Stream.of(“aa”,”bb”,”cc”);
  4. 無限流

    • 迭代

      Stream.iterate(0, (x) -> x+2 )
      .forEach(System.out::println);

    • 生成

      Stream.generate(()-> Math.random())
      .forEach(System.out::println);

二、中間操作

多箇中間操作可以連線起來形成一個流水線,除非流水線上觸發終止操作,否則中間操作不會執行任何處理。而在終止操作是一次性全部處理,稱為“惰性求值

2.1 篩選與切片
 List<Student> students = Arrays.asList(
            new
Student("張三",18,88), new Student("李四",18,80), new Student("王五",19,60), new Student("王五",19,60), new Student("王五",19,60), new Student("趙六",17,100) ); // 1.過濾 @Test public void test(){ //中間操作 Stream<Student> studentStream = students.stream() .filter(s -> s.getAge() > 17
); //終止操作 studentStream.forEach(System.out::println); } //2.limit(n) :前幾個 @Test public void test2(){ students.stream() .filter(s-> s.getScore()>70) .limit(2) .forEach(System.out::println); } //3. skip(n) 跳過前n個 @Test public void test3(){ students.stream() .filter(s->s.getAge()>17) .skip(1) //跳過 .forEach(System.out::println); } // 4. distinct() 去重 @Test public void test4(){ students.stream() .filter(s->s.getAge()>17) .skip(1) //跳過 .distinct() //去重,需要物件重寫hashCode() equals() 兩個方法 .forEach(System.out::println); }
2.2 對映 map和flatMap
  • map : 接收 Lambda , 將元素轉換成其他形式或提取資訊。接收一個函式作為引數,該函式會被應用到每個元素上,並將其對映成一個新的元素。
 public static Stream<Character> getCharacterStream(String str){
        List<Character> characters = new ArrayList<>();
        for (Character c: str.toCharArray()) {
            characters.add(c);
        }
        return characters.stream();
    }
  @Test
  public void testMap(){
        List<String> list = Arrays.asList("aaa","bbb","ccc");
        Stream<Stream<Character>> chStream = list.stream()
                .map(s-> getCharacterStream(s));
        chStream.forEach(stream -> {
            stream.forEach(System.out::println);
        });
        System.out.println("--------------------------------");
    }
  • flatMap : 接收一個函式作為引數,將流中的每個值都換成另一個流,然後把所有流連線成一個流
    @Test
    public void testFlatMap(){
        List<String> list = Arrays.asList("aaa","bbb","ccc");
        Stream<Character> flatStream = list.stream()
                .flatMap(s-> getCharacterStream(s));
        flatStream.forEach(System.out::println);
    }

總結:
- map返回一個流,或者多個流的集合
- flatMap 是每個元素都合併到一個流中,最終產生一個流

2.3 排序
  • sorted() : 自然排序
  • sorted(Comparator com) :定製排序
/*
預設排序
*/
 @Test
    public void testSorted(){
        List<String> list = Arrays.asList("aaa","BBB","AAA","aaa","ccc","CCC");
                 list.stream()
                     .sorted()
                     .forEach(System.out::println);
    }

//資料
 List<Student> students = Arrays.asList(
            new Student("張三",18,88),
            new Student("李四",18,80),
            new Student("王五",19,60),
            new Student("王五",19,60),
            new Student("王五",19,60),
            new Student("趙六",17,100)
    );
 //自定義排序
 @Test
    public void testSorted2(){
        //先轉換(List<T>->List<U>),然後排序
        students.stream()
                .map(Student::getAge)
                .sorted(Comparator.comparingInt(s -> s))
                .forEach(System.out::println);
        //直接排序
        students.stream()
                .sorted((s1,s2)->{
                    if (s1.getAge() == s2.getAge()){
                        return Integer.compare(s1.getScore(),s2.getScore());
                    }else
                        return Integer.compare(s1.getAge(),s2.getAge());
                })
                .forEach(System.out::println);
    }