過濾字符串長度爲1的字符串
public static void filter() { Stream.of("1", "2", "3", "11", "22", "33") .filter((str) -> str.length() == 1) .forEach(System.out::println); }
這邊filter傳遞的是Predicate,返回的是boolean值。
運行結果以下:數據庫
去掉重複的字符串
public static void distinct() { Stream.of("1", "2", "3", "1", "2") .distinct() .forEach(System.out::println); }
和數據庫的distinct是相似的。
運行結果以下:segmentfault
取字符串的前面三個
public static void limit() { Stream.of("1", "2", "3", "11", "22", "33") .limit(3) .forEach(System.out::println); }
運行結果以下:數組
跳過前面三個字符串
public static void skip() { Stream.of("1", "2", "3", "11", "22", "33") .skip(3) .forEach(System.out::println); }
與limit相反。
運行結果以下:函數
對數字排序
public static void sorted() { Stream.of(1, 3, 2, 4) .sorted() .forEach(System.out::println); } public static void sorted2() { Stream.of(1, 3, 2, 4) .sorted(Integer::compareTo) .forEach(System.out::println); }
能夠默認排序,也能夠自定義排序。
運行結果以下:性能
對流的中間過程進行打印
public static void peek() { Stream.of("1", "2", "3", "11", "22", "33") .filter((str) -> str.length() == 1) .peek((t)->{ System.out.print(t); System.out.println("sorted"); }) .sorted() .peek((t)->{ System.out.print(t); System.out.println("sorted2"); }) .limit(2) .peek((t)->{ System.out.print(t); System.out.println("sorted3"); }) .collect(Collectors.toList()); }
peek中傳的是Consumer。
運行結果以下:spa
把1,2,3轉換成N的平方
map是映射的意思,接受一個函數做爲參數。這個函數會被應用到每一個元素上,並將其映射成一個新的元素3d
public static void map() { Stream.of(1, 2, 3) .map(n -> n * n) .forEach(System.out::println); }
運行結果以下:code
把1,2,3轉換成N的平方,再求和
public static void mapToInt() { int sum = Stream.of(1, 2, 3) .mapToInt(n -> n * n) .sum(); System.out.println(sum); }
獲得的結果是14,mapToInt主要是返回int的流,爲了不裝拆箱帶來的性能消耗。
其餘的mapToLong
、mapToDouble
雷同blog
對字符串數組去重並輸出
Stream.of(new String[]{"123", "345"}) .map((s) -> s.split("")) .flatMap(Arrays::stream) .distinct() .forEach(System.out::println);
運行結果以下:
在map映射後,獲得的是Stream<String[]>的流,而後再經過flatMap的扁平化處理,轉化爲Stream<String>的流。
其餘的flatMapToInt
、flatMapToLong
、flatMapToDouble
雷同。排序