1. 程式人生 > >java8 流操作

java8 流操作

1  合併多個流

    //合併多個流 
    private void merge() {
        List<String> list = new ArrayList<String>();
        list.add("I am a boy");
        list.add("I love the girl");
        list.add("But the girl loves another girl");
        
        List<String> result = list.stream() //
得到流 .map(line->line.split(" ")) //將每個元素轉成String[] .flatMap(Arrays::stream) //將每個String[] 轉成流 ,併合併為一個大流 .distinct() //對元素去重 .collect(Collectors.toList()); //終止流得到集合 result.forEach(System.out::println); //列印 }

2  是否匹配任一元素

    //是否匹配任一元素
    private
void anyMatch() { List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19)); boolean isHas = persons.stream().anyMatch(e -> e.getAge() == 18); System.out.println("isHas : "+isHas); }

3  是否所有元素都匹配

    //是否所有元素都匹配
    private
void allMatch() { List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19)); boolean bool = persons.stream().allMatch(e -> e.getAge() == 18); System.out.println("isHas : "+bool); }

 

4  是否所有元素都不匹配

    //是否所有元素都不匹配
    private void  noneMatch() {
    
        List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19));
        boolean bool = persons.stream().noneMatch(e -> e.getAge() == 20);
        System.out.println("isHas : "+bool);
    }

 5 新增容器optional  (儲存一個物件或者不存,可以避免空指標異常)

    private void  findFirst() {
    
        List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19));
        Optional<Person>  optional = persons.stream().findFirst();
        System.out.println(optional.get().getName());
        
    }

 

6  歸併  reduce

    //歸併
    private void  testReduce() {
        List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19));
        //reduce 不設定初始值
        Optional<Integer> optional = persons.stream().map(e -> e.getAge()).reduce((a,b) -> a + b);
        System.out.println(optional.get());
        //reduce 設定初始值
        Integer ageTotal = persons.stream().map(e -> e.getAge()).reduce(0,(a,b) -> a + b);
        System.out.println(ageTotal);
    }