Stream常用流操作

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

collect(toList())

由Stram里的值生成一个列表,是一个及早求值操作

List collect = Stream.of("a", "b", "c")  // 由列表生成一个Stream
                .collect(Collectors.toList());   // 由Stream生成一个列表

map

将一种类型的值转换成另外一种类型,将一个流中的值转换成一个新的流

// 将集合中的字符串装换成大写形式
List collect = Stream.of("a", "b", "hello").map(string -> string.toUpperCase())
                .collect(Collectors.toList());

filter

遍历数据并检查、过滤其中的元素

// 过滤字符串集合中长度大于1的数据
List collect = Stream.of("a", "1abc", "abc1")
                .filter(value -> value.length() > 1)
                .collect(Collectors.toList());

flatMap

可用Stream替换值,然后将多个Stream连接成一个Stream

List collect = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4))
                .flatMap(numbers -> numbers.stream())
                .collect(Collectors.toList());

Max、Min

public class Track {

    private String name;
    private int length;

    public Track(String name, int length) {
        this.name = name;
        this.length = length;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    @Override
    public String toString() {
        return "Track{" +
                "name='" + name + '\'' +
                ", length=" + length +
                '}';
    }
}
List tracks = Arrays.asList(new Track("Bakal", 524),
                new Track("Violets for Your Furs", 378),
                new Track("Time Was", 451));
        Track shortestTrack = tracks.stream()
                .min(Comparator.comparing(track -> track.getLength())).get();

reduce

可以实现从一组值中生成一个值,上述例子中用到的count、min和max方法,因为常用而被纳入标准库中,事实上,这些方法都是reduce操作

// 获取累加的值,reduce第一个参数是初始值
Integer count = Stream.of(1, 2, 3)
                .reduce(0, (acc, element) -> acc + element);
        System.out.println(count);

// 展开reduce操作
BinaryOperator accumulator = (acc, element) -> acc + element;
Integer count = accumulator.apply(accumulator.apply(accumulator.apply(0, 1), 2), 3);

 

转载于:https://my.oschina.net/u/3198904/blog/1788487

你可能感兴趣的:(Stream常用流操作)