Java8 Stream

建立無限流

  1. 迭代
Stream<Integer> iterate = Stream.iterate(0, x -> x + 2);
iterate.forEach(System.out::println);
//iterate.limit(10).forEach(System.out::println);

會從0開始+2的方式一直輸出數據,若是隻想要前10個,就加上limit。java

  1. 生成
Stream.generate(() -> Math.random()).forEach(System.out::println);

無限生成隨機數。app

篩選和切片(中間操做)

多箇中間操做能夠鏈接起來造成一個流水線,除非流水線觸發終止操做,不然中間操做不會執行任何處理,而在終止操做時一次性所有處理,稱爲「惰性求值」。dom

  1. distinct() 的去重是依賴 equals()hashCode()
List<UserTest> list = new ArrayList<>();
list.add(new UserTest(1, "李四"));
list.add(new UserTest(1, "李四"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(3, "趙六"));
list.stream().distinct().forEach(System.out::println);

在沒有重寫 UserTestequalshashCode
ide


UserTest{id=1, name='李四'}
UserTest{id=1, name='李四'}
UserTest{id=2, name='王五'}
UserTest{id=2, name='王五'}
UserTest{id=3, name='趙六'}

重寫 UserTestequalshashCode

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof UserTest)) return false;
    UserTest userTest = (UserTest) o;
    if (id != userTest.id) return false;
    return name != null ? name.equals(userTest.name) : userTest.name == null;
}
@Override
public int hashCode() {
    int result = id;
    result = 31 * result + (name != null ? name.hashCode() : 0);
    return result;
}

UserTest{id=1, name='李四'}
UserTest{id=2, name='王五'}
UserTest{id=3, name='趙六'}函數

  1. filter 接收Lambda,從流中排除某些元素this

  2. limit 截斷流,使其元素不超過指定個數code

  3. skip 跳過元素,返回一個扔掉了前n個元素的流, 若流中元素不夠n個則返回一個空流,與limit互補。排序

映射(中間操做)

  1. map 接收一個函數做爲參數,該函數會被應用到每一個元素上,並將其映射到成一個新的元素。
List<String> list = Arrays.asList("aaa", "nnn", "vvv");
Stream<Stream<Character>> streamStream = list.stream().map(OperateTest::filterCharacter);
streamStream.forEach((sm) -> sm.forEach(System.out::println));
  1. flatMap 接收一個函數做爲參數,將流中的每一個值都換成另外一個流,而後把全部的流鏈接成一個流。
Stream<Character> characterStream = list.stream().flatMap(OperateTest::filterCharacter);
characterStream.forEach(System.out::println);

根據 mapflatMap 的返回值能夠知道, map 返回的是嵌套流,flatMap 是返回一個流,打印以後的結果是同樣的,map 返回的嵌套流會在後面的輸出時,屢次變量,而 flatMap 就很好的解決了這個問題。接口

排序(中間操做)

  1. sorted() 天然排序ip

  2. sorted(Comparator com) 定製排序
list.stream().sorted(Comparator.comparing(UserTest::getId).thenComparing(UserTest::getName)).forEach(System.out::println);

查找與匹配(終止操做)

  1. allMatch 檢查是否匹配全部元素
boolean result = list.stream().allMatch(e -> e.getName().equals("李四"));
System.out.println(result); // false
  1. anyMatch 檢查是否至少匹配一個元素
boolean result = list.stream().anyMatch(e -> e.getName().equals("李四"));
System.out.println(result); // true
  1. noneMath 是否沒有匹配全部元素
boolean reuslt = list.stream().noneMatch(e -> e.getName().equals("田七"));
System.out.println(reuslt); // true
  1. findFirst 返回第一個元素
Optional<UserTest> first = list.stream().sorted(Comparator.comparing(UserTest::getId)).findFirst();
System.out.println(first.get());

按照id排序以後,返回第一個元素。

  1. findAny 返回當前流中的任意元素
Optional<UserTest> result = list.parallelStream().filter(e -> e.getName().equals("李四")).findAny();
System.out.println(result.get());
  1. count 返回元素的個數

  2. max 返回最大值
Optional<UserTest> max = list.stream().max(Comparator.comparing(UserTest::getId));
System.out.println(max);
  1. min 返回最小值
Optional<Integer> min = list.stream().map(UserTest::getId).min(Integer::compareTo);
System.out.println(min);

歸約(終止操做)

  1. reduce(T identity, BinaryOperator) / reduce(BinaryOperator) 能夠將流中元素反覆結合起來,返回一個值
Integer reduce = list.stream().map(UserTest::getId).reduce(0, (x, y) -> x + y);
System.out.println(reduce);
Optional<Integer> reduce = list.stream().map(UserTest::getId).reduce(Integer::sum);
System.out.println(reduce.get());

使用 mapreduce

List<UserTest> list = new ArrayList<>();
list.add(new UserTest(1, "李四"));
list.add(new UserTest(1, "李四"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(3, "趙六"));
Optional<Integer> reduce = list.stream().map(UserTest::getId).reduce(Integer::sum);
System.out.println(reduce.get());

收集(終止操做)

collect(Collector c) 將流轉換成其餘形式,接收一個Collector接口的實現,用於給Stream中元素作彙總的方法

  1. toList() 返回list集合

  2. toSet() 返回set集合

  3. toCollection(HashSet::new)

  4. counting() 獲取總數

  5. averagingInt(ToIntFunction mapper) 獲取平均值
Double collect = list.stream().collect(Collectors.averagingInt(UserTest::getId));
  1. summingInt(ToIntFunction mapper) 獲取總和
Integer collect = list.stream().collect(Collectors.summingInt(UserTest::getId));
  1. maxBy 最大值(不建議使用,建議直接使用上面的max())
Optional<UserTest> collect = list.stream().collect(Collectors.maxBy(Comparator.comparing(UserTest::getId)));
  1. groupingBy 分組
Map<Integer, List<UserTest>> collect = list.stream().collect(Collectors.groupingBy(UserTest::getId));
  1. partitioningBy 分區
Map<Boolean, List<UserTest>> collect = list.stream().collect(Collectors.partitioningBy(e -> e.getId() > 3));
System.out.println(collect);

輸出

{false=[UserTest{id=1, name='李四'}, UserTest{id=2, name='王五'}, UserTest{id=1, name='李四'}, UserTest{id=3, name='趙六'}], true=[UserTest{id=5, name='王五'}]}

相關文章
相關標籤/搜索