参考博客: https://www.jianshu.com/p/9fe8632d0bc2

 

 

参考:https://www.cnblogs.com/xumBlog/p/9507936.html

 

Stream 简介

  • Java 8 引入了全新的 Stream API。这里的 Stream 和 I/O 流不同,它更像具有 Iterable 的集合类,但行为和集合类又有所不同。
  • stream 是对集合对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作。
  • 只要给出需要对其包含的元素执行什么操作,比如 “过滤掉长度大于 10 的字符串”、“获取每个字符串的首字母” 等,Stream 会隐式地在内部进行遍历,做出相应的数据转换。

为什么要使用 Stream

  • 函数式编程带来的好处尤为明显。这种代码更多地表达了业务逻辑的意图,而不是它的实现机制。易读的代码也易于维护、更可靠、更不容易出错。

 

这里给出 Main 方法的代码:

package com.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test {

    public static void main(String[] args) {
        
        List<Person> list = new ArrayList<Person>();
        
        Person p1 = new Person("a", 11, "aaaaa");
        Person p2 = new Person("b", 12, "bbbbb");
        Person p3 = new Person("c", 13, "ccccc");
        Person p4 = new Person("d", 14, "ddddd");
        Person p5 = new Person("e", 15, "eeeee");
        
        list = Arrays.asList(p1, p2, p3, p4, p5);
        filterTest(list);
        mapTest(list);
        flatMapTest(list);
        reduceTest();
        collectTest(list);
    }
    
    private static void println(List<Person> list) {
        for(Person p:list) {
            System.out.println(p.getName()+"-"+p.getAge()+"-"+p.getProvince());
        }
    }
    
    // filter age > 13 and name = d 
    private static void filterTest(List<Person> list) {
        List<Person> temp = new ArrayList<Person>();
        for(Person p:list) {
            if (p.getAge() > 13 && "d".equalsIgnoreCase(p.getName())) {
                temp.add(p);
            }
        }
        println(temp);
        
        List<Person> collect = list
                .stream()
                .filter(p->(p.getAge() > 13 && "d".equalsIgnoreCase(p.getName())))
                .collect(Collectors.toList());
        println(collect);
        
        List<Person> collect1 = list
                .stream()
                .filter(p->{
                    if (p.getAge() > 13 && "d".equalsIgnoreCase(p.getName())) {
                        return true;
                    }
                    return false;
                })
                .collect(Collectors.toList());
        println(collect1);
    }
    
    // map
    private static void mapTest(List<Person> list) {
        List<String> temp = new ArrayList<>();
        for(Person p:list) {
            temp.add(p.getName());
        }
        System.out.println("temp="+temp.toString());
        
        List<String> collect = list
                .stream()
                .map(p->p.getName())
                .collect(Collectors.toList());
        System.out.println("collect="+collect);
        
        List<String> collect1 = list
                    .stream()
                    .map(Person::getName)
                    .collect(Collectors.toList());
        System.out.println("collect1="+collect1);

        List<String> collect2 = list
                    .stream()
                    .map(p->{
                        return p.getName();
                    }).collect(Collectors.toList());
        System.out.println("collect2="+collect2);
    }
    
    // flatMap
    private static void flatMapTest(List<Person> list) {
        List<String> collect = list
                .stream()
                .flatMap(person -> Arrays.stream(person.getName().split(" ")))
                .collect(Collectors.toList());
        System.out.println("collect="+collect);

        List<Stream<String>> collect1 = list
                    .stream()
                .map(person -> Arrays.stream(person.getName().split(" ")))
                .collect(Collectors.toList());
        System.out.println("collect1="+collect1);
   
        List<String> collect2 = list
                    .stream()
                .map(person -> person.getName().split(" "))
                .flatMap(Arrays::stream)
                .collect(Collectors.toList());
        System.out.println("collect2="+collect2);

        List<String> collect3 = list
                    .stream()
                .map(person -> person.getName().split(" "))
                .flatMap(str -> Arrays.asList(str).stream())
                .collect(Collectors.toList());
        System.out.println("collect3="+collect3);
    }
    
    // reduce
    public static void reduceTest(){
        Integer reduce = Stream.of(1, 2, 3, 4)
                .reduce(10, (count, item) ->{
            System.out.println("count:"+count);
            System.out.println("item:"+item);
            return count + item;
        } );
        System.out.println(reduce);

        Integer reduce1 = Stream.of(1, 2, 3, 4)
                .reduce(1, (x, y) -> x + y);
        System.out.println(reduce1);

        String reduce2 = Stream.of("1", "2", "3")
                .reduce("1", (x, y) -> (x + "," + y));
        System.out.println(reduce2);
    }

    /**
     * toList
     */
    public static void collectTest(List<Person> list){
        List<String> collect = list.stream()
                .map(Person::getName)
                .collect(Collectors.toList());
        
        Set<String> collect1 = list.stream()
                .map(Person::getName)
                .collect(Collectors.toSet());
        
        Map<String, Integer> collect2 = list.stream()
                .collect(Collectors.toMap(Person::getName, Person::getAge));
        Map<String, String> collect3 = list.stream()
                .collect(Collectors.toMap(p->p.getName(), value->{
            return value+"1";
        }));
        for (Map.Entry<String, String> entry : collect3.entrySet()) {
                 System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
            }
        
        //TreeSet<Person> collect4 = list.stream()
        //        .collect(Collectors.toCollection(TreeSet::new));
        //System.out.println(collect4);
        
        Map<Boolean, List<Person>> collect5 = list.stream()
                .collect(Collectors.groupingBy(p->"d".equalsIgnoreCase(p.getName())));
        System.out.println(collect5);
        
        String collect6 = list.stream()
                .map(p->p.getName())
                .collect(Collectors.joining(",", "{", "}"));
        System.out.println(collect6);
        
        List<String> collect7 = Stream.of("1", "2", "3").collect(
                Collectors.reducing(new ArrayList<String>(), x -> Arrays.asList(x), (y, z) -> {
                    y.addAll(z);
                    return y;
                }));
        System.out.println(collect7);
    }


}

 

posted on 2019-05-05 17:58  lshan  阅读(240)  评论(0编辑  收藏  举报