Java8 - Stream API數組
流一旦使用終止操做,就不能再進行中間操做app
參考Java8 - Lambda表達式dom
多箇中間操做能夠鏈接起來造成一個流水線,除非流水 線上觸發終止操做,不然中間操做不會執行任何的處理!而在終止操做時一次性所有處理,稱爲「惰性求值」。ide
default Stream<E> stream() {return StreamSupport.stream(spliterator(), false);}函數
default Stream<E> parallelStream() {return StreamSupport.stream(spliterator(), true);}工具
Collection<Integer> collection = new ArrayList<Integer>(); collection.add(1); collection.add(2); collection.add(3); collection.add(4); // 串行流 Stream<Integer> stream1 = collection.stream(); // 並行流 Stream<Integer> stream2 = collection.parallelStream();
public static <T> Stream<T> stream(T[] array)ui
public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive).net
public static IntStream stream(int[] array) ...code
public static LongStream stream(long[] array) ...對象
public static DoubleStream stream(double[] array) ...
Integer[] array = new Integer[]{1, 2, 3, 4}; Stream<Integer> stream1 = Arrays.stream(array);
public static<T> Stream<T> of(T... values)
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4);
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
public static<T> Stream<T> generate(Supplier<T> s)
Stream<Integer> stream1 = Stream.iterate(1, (t) -> t + 2); Stream<Double> stream1 = Stream.generate(() -> new Random().nextInt(100));
public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
Stream<T> filter(Predicate<? super T> predicate);
Stream<Student> stream2 = stream1.filter((t) -> { if (t.getAge() >= 18) { return true; } return false; });
Stream<T> limit(long maxSize); 截取前N個元素
Stream<T> skip(long n); 忽略前N個元素
Stream<T> distinct();
以對象的 hashCode() 和 equals() 來斷定是不是同一個元素
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
IntStream mapToInt(ToIntFunction<? super T> mapper);
LongStream mapToLong(ToLongFunction<? super T> mapper);
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
...
Stream<Student> stream2 = stream1.map((o) -> { if (o.getName().contains("敏感詞彙")) { o.setName(o.getName().replaceAll("敏感詞彙","*")); } return o; }); Stream<String> stream2 = stream1.map(Student::getName);
對比 flatMap 和 map 的區別: flatMap會將結果拼裝成一個總體
public void test7() { List<String> list = Arrays.asList("hello", "world", "gq"); Stream<Stream<Character>> stream = list.stream().map(StreamAPIOperrateDemo::stringToCharacter); Stream<Character> stream2 = list.stream().flatMap(StreamAPIOperrateDemo::stringToCharacter); stream.forEach((sm) -> sm.forEach(System.out::print)); // System.out.println(); stream2.forEach(System.out::print); // } private static Stream<Character> stringToCharacter(String string) { List<Character> characterList = new ArrayList<>(); char[] chars = string.toCharArray(); for (Character ch : chars) { characterList.add(ch); } return characterList.stream(); }
Stream<T> sorted();
前提:T 實現 Comparable 接口
Stream<T> sorted(Comparator<? super T> comparator);
//Stream<Student> stream2 = stream1.sorted(); //Stream<Student> stream2 = stream1.sorted(new StudentComparator()); //Stream<Student> stream2 = stream1.sorted((s1, s2) -> s1.getAge() - s2.getAge()); Stream<Student> stream2 = stream1.sorted((s1, s2) -> Integer.compare(s1.getAge(),s2.getAge())); // 推薦 Stream<Student> stream3 = stream1.sorted(Comparator.comparingInt(Student::getAge));
boolean allMatch(Predicate<? super T> predicate);
檢查是否匹配全部元素
boolean anyMatch(Predicate<? super T> predicate);
檢查是否至少匹配一個元素
boolean noneMatch(Predicate<? super T> predicate);
檢查是否沒有匹配的元素
Optional<T> findFirst();
返回第一個元素
Optional<T> findAny();
返回當前流中的任意元素
long count();
返回流中元素的總個數
Optional<T> max(Comparator<? super T> comparator);
返回流中最大值
Optional<Integer> maxAge = stream1.distinct().map(Student::getAge).max(Integer::compare);
Optional<T> min(Comparator<? super T> comparator);
返回流中最小值
T reduce(T identity, BinaryOperator<T> accumulator);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer sum = list.stream().reduce(0, (x, y) -> x + y); System.out.println(sum);
Optional<T> reduce(BinaryOperator<T> accumulator);
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
List<String> list = Arrays.asList("June", "Kmde", "Kang", "Zhan", "Gui"); Optional<String> result = list.stream().reduce((x, y) -> x + "_" + y); System.out.println(result.get());
Integer sum = stream1.distinct().map(Student::getAge).reduce(0, (x, y) -> x + y); Optional<Integer> sum = stream1.distinct().map(Student::getAge).reduce(Integer::sum);
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);
<R, A> R collect(Collector<? super T, A, R> collector);
能夠藉助Collectors
工具類進行構建Collector
對象;
能夠轉化成List、Set、Map ...
List<String> names = stream1.map(Student::getName).collect(Collectors.toList()); Set<String> names = stream1.map(Student::getName).collect(Collectors.toSet()); Set<String> names = stream1.map(Student::getName).collect(Collectors.toCollection(HashSet::new)); Map<Integer, String> names = stream1.distinct().collect(Collectors.toMap(Student::getId, Student::getName));
彙總 總量、總數值、平均值、最大最小值...
Long count = stream1.collect(Collectors.counting()); Double sum = stream1.collect(Collectors.summingDouble(Student::getHeight)); Double avg = stream1.collect(Collectors.averagingDouble(Student::getHeight)); Optional<Student> optionalStudent = stream1.collect(Collectors.maxBy(Comparator.comparingDouble(Student::getHeight))); // 彙總統計 DoubleSummaryStatistics sum = stream1.collect(Collectors.summarizingDouble(Student::getHeight)); System.out.println(sum.getCount()); System.out.println(sum.getSum()); System.out.println(sum.getAverage()); System.out.println(sum.getMax()); System.out.println(sum.getMin());
Map<Integer, List<Student>> stuMap = stream1.collect(Collectors.groupingBy(Student::getAge)); stuMap.forEach((key, value) -> { System.out.println("age:" + key); value.forEach(System.out::println); }); // ---- Map<Integer, Map<String, List<Student>>> stuMap = stream1.collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(t -> { if (t.getHeight() >= 1.80) { return "挺高"; } else if (t.getHeight() <= 1.60) { return "偏矮"; } else { return "正常"; } }))); stuMap.forEach((key, value) -> { System.out.println("age:" + key); value.forEach((k, v) -> { System.out.println("height" + k); v.forEach(System.out::println); }); });
Map<Boolean, List<Student>> booleanListMap = stream1.collect(Collectors.partitioningBy(t -> t.getAge() >= 18)); booleanListMap.forEach((key, value) -> { System.out.println("age:" + key); value.forEach(System.out::println); });
String names = stream1.map(Student::getName).collect(Collectors.joining(",", "<Start>", "<End>"));