Stream經常使用流操做

collect(toList())

由Stram裏的值生成一個列表,是一個及早求值操做java

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

map

將一種類型的值轉換成另一種類型,將一個流中的值轉換成一個新的流app

// 將集合中的字符串裝換成大寫形式
List<String> collect = Stream.of("a", "b", "hello").map(string -> string.toUpperCase())
                .collect(Collectors.toList());

filter

遍歷數據並檢查、過濾其中的元素ide

// 過濾字符串集合中長度大於1的數據
List<String> collect = Stream.of("a", "1abc", "abc1")
                .filter(value -> value.length() > 1)
                .collect(Collectors.toList());

flatMap

可用Stream替換值,而後將多個Stream鏈接成一個Streamthis

List<Integer> 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<Track> 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操做spa

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

// 展開reduce操做
BinaryOperator<Integer> accumulator = (acc, element) -> acc + element;
Integer count = accumulator.apply(accumulator.apply(accumulator.apply(0, 1), 2), 3);
相關文章
相關標籤/搜索