最近寫較復雜業(yè)務邏輯代碼的時候,對集合中數(shù)據(jù)進行篩選處理時一不注意就寫了超過一百行代碼了,可讀性和維護性都比較差,所以周末花時間研究下java8 Stream
Sream API
Stream分為三種類型,一種是Intermediate,一種是Terminal還有一種是short-circuiting
- Intermediate:一個流后面可以跟一個或多個Intermediate操作,它會對流進行處理然后返回一個新的流.常見的Intermediate操作有map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
- Terminal:terminal 操作是流的最后一個操作.Terminal操作有forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator
- short-circuiting有2種類型:
1.對于一個 intermediate 操作,如果它接受的是一個無限大(infinite/unbounded)的 Stream,但返回一個有限的新 Stream。
2.對于一個 terminal 操作,如果它接受的是一個無限大的 Stream,但能在有限的時間計算出結果。
常見的short-circuiting操作有anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit
Stream API實踐
//常用Stream api的使用
List<Integer> nums = Arrays.asList(6,43,67,76,12,4,5,235,7,6,7,null);
List<Integer> result = nums.stream()
.filter(i -> i!= null && i > 4) //filter過濾
.distinct() //distinct去重
.sorted((i1,i2) -> i1.compareTo(i2)) //sorted排序
.skip(1) //skip跳過前一個元素
.limit(5) //limit取前5個元素
.map(i -> i+1) //map轉化為另一個對象,map生成的是1:1的映射
.peek(i ->System.out.print(i + " ")) //peek為每個元素包裝Consumer
.collect(Collectors.toList()); //轉為List,和toArray類型
result.parallelStream().forEach(System.out::println); //foreach和parallelStream并發(fā)處理不保證順序
result.stream().max((i1,i2) -> i1.compareTo(i2)).get(); //max
Stream<List<Integer>> stream = Stream.of(
Arrays.asList(1),
Arrays.asList(2, 3),
Arrays.asList(4, 5, 6)
);
//[[1], [2, 3], [4, 5, 6]]
stream.collect(Collectors.toList()).toString();
//[1, 2, 3, 4, 5, 6]
stream.flatMap(list -> list.stream()).collect(Collectors.toList()).toString(); //flatMap生成的是1:n的映射
//reduce是一個聚合的方法,有2個參數(shù),第一個參數(shù)是初始值,第二個參數(shù)是一個運算規(guī)則,reduce通過運算規(guī)則將初始值和
//所有的Stream元素聚合,當沒有初始值時返回Optional對象如sumValue
// 字符串連接,concat = "ABCD"
String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
// 求最小值,minValue = -3.0
double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
// 求和,sumValue = 10, 有起始值
int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
// 求和,sumValue = 10, 無起始值
sumValue = Stream.of(1,2,3).reduce(Integer::sum).get();
// 過濾,字符串連接,concat = "ace"
concat = Stream.of("a", "B", "c", "D", "e", "F").
filter(x -> x.compareTo("Z") > 0).
reduce("", String::concat);
代碼:https://github.com/redaCode/CodeJDK
參考:
1.https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html
2.http://ifeve.com/stream/