資料流(Stream)的使用
1) Stream 的擷取
① 通過集合Collection擷取
1
List<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
2
Stream<Integer> stream = list.stream();
② 通過數組擷取
1
String[] array = {"are","you","ok"};
2
Stream<String> stream = Array.stream(array);
3
4
//對於基本類型數組的處理
5
int[] array = {1,2,3,4,5};
6
Stream<Integer> stream = Arrays.stream(array).boxed(); //此時Arrays.stream(array)擷取的是一個IntStream對象
③ 通過值擷取(盡量使用以上2種方式擷取,這種方式存在缺陷)
1
Stream<String> stream = Stream.of("are","you","ok");
2) 篩選 filter
filter函數接收一個Lambda運算式作為參數,該運算式返回boolean,在執行過程中,流將元素逐一輸送給filter,並篩選出執行結果為true的元素;
1
//篩選出列表中的非空項
2
List<String> list = Arrays.asList("are","you","","ok");
3
List<String> filted = list.stream()
4
.filter(x-> !x.empty())
5
.collect(Collectors.toList());
3) 去重 distinct
1
List<String> list = Arrays.asList("are","you","you","ok");
2
List<String> distincted = list.stream()
3
.distinct()
4
.collect(Collectors.toList());
4) 截取 limit
截取流的前N個元素: