Skip to content

Commit 874c3c4

Browse files
committed
[add] add some stream api examples
1 parent dec2180 commit 874c3c4

File tree

8 files changed

+242
-5
lines changed

8 files changed

+242
-5
lines changed

java8/src/main/java/com/brianway/learning/java8/lambda/FilteringApples.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
/**
99
* Created by brian on 16/12/26.
10+
*
11+
*
1012
*/
1113
public class FilteringApples {
1214
public static void main(String[] args) {

java8/src/main/java/com/brianway/learning/java8/streamapi/BuildingStreams.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import java.util.stream.IntStream;
99
import java.util.stream.Stream;
1010

11+
/**
12+
* 斐波拉切数列的几种生成方法
13+
*/
1114
public class BuildingStreams {
1215

1316
public static void main(String... args) throws Exception {
@@ -48,11 +51,8 @@ public static void main(String... args) throws Exception {
4851
.limit(5)
4952
.forEach(System.out::println);
5053

51-
IntStream.generate(new IntSupplier() {
52-
public int getAsInt() {
53-
return 2;
54-
}
55-
}).limit(5)
54+
IntStream.generate(() -> 2)
55+
.limit(5)
5656
.forEach(System.out::println);
5757

5858
IntSupplier fib = new IntSupplier() {

java8/src/main/java/com/brianway/learning/java8/streamapi/GroupingTransactions.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import java.util.List;
99
import java.util.Map;
1010

11+
/**
12+
* 分别使用指令式和函数式进行分组
13+
*/
1114
public class GroupingTransactions {
1215

1316
public static List<Transaction> transactions = Arrays.asList(
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static java.util.stream.Collectors.toList;
4+
5+
import java.util.Arrays;
6+
import java.util.List;
7+
8+
/**
9+
* 流操作-中间操作
10+
*/
11+
public class Laziness {
12+
13+
public static void main(String[] args) {
14+
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
15+
List<Integer> twoEvenSquares =
16+
numbers.stream()
17+
.filter(n -> {
18+
System.out.println("filtering " + n); return n % 2 == 0;
19+
})
20+
.map(n -> {
21+
System.out.println("mapping " + n);
22+
return n * n;
23+
})
24+
.limit(2)
25+
.collect(toList());
26+
27+
twoEvenSquares.stream().forEach(System.out::println);
28+
}
29+
30+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static com.brianway.learning.java8.streamapi.Dish.menu;
4+
import static java.util.stream.Collectors.toList;
5+
6+
import java.util.Arrays;
7+
import java.util.List;
8+
9+
/**
10+
* 使用流-映射
11+
* 注意扁平映射
12+
*/
13+
public class Mapping {
14+
15+
public static void main(String... args) {
16+
17+
// map
18+
List<String> dishNames = menu.stream()
19+
.map(Dish::getName)
20+
.collect(toList());
21+
System.out.println(dishNames);
22+
23+
// map
24+
List<String> words = Arrays.asList("Hello", "World");
25+
List<Integer> wordLengths = words.stream()
26+
.map(String::length)
27+
.collect(toList());
28+
System.out.println(wordLengths);
29+
30+
// flatMap
31+
words.stream()
32+
.flatMap((String line) -> Arrays.stream(line.split("")))
33+
.distinct()
34+
.forEach(System.out::println);
35+
36+
// flatMap
37+
List<Integer> numbers1 = Arrays.asList(1, 2, 3, 4, 5);
38+
List<Integer> numbers2 = Arrays.asList(6, 7, 8);
39+
List<int[]> pairs =
40+
numbers1.stream()
41+
.flatMap((Integer i) -> numbers2.stream()
42+
.map((Integer j) -> new int[] {i, j})
43+
)
44+
.filter(pair -> (pair[0] + pair[1]) % 3 == 0)
45+
.collect(toList());
46+
pairs.forEach(pair -> System.out.println("(" + pair[0] + ", " + pair[1] + ")"));
47+
}
48+
}
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static java.util.stream.Collector.Characteristics.IDENTITY_FINISH;
4+
import static java.util.stream.Collectors.partitioningBy;
5+
6+
import java.util.ArrayList;
7+
import java.util.Collections;
8+
import java.util.EnumSet;
9+
import java.util.HashMap;
10+
import java.util.List;
11+
import java.util.Map;
12+
import java.util.Set;
13+
import java.util.function.BiConsumer;
14+
import java.util.function.BinaryOperator;
15+
import java.util.function.Function;
16+
import java.util.function.Predicate;
17+
import java.util.function.Supplier;
18+
import java.util.stream.Collector;
19+
import java.util.stream.IntStream;
20+
import java.util.stream.Stream;
21+
22+
/**
23+
* 分区:分类的特殊情况。分区函数返回一个布尔值
24+
*/
25+
public class PartitionPrimeNumbers {
26+
27+
public static void main(String... args) {
28+
System.out.println("Numbers partitioned in prime and non-prime: " + partitionPrimes(100));
29+
System.out.println("Numbers partitioned in prime and non-prime: " + partitionPrimesWithCustomCollector(100));
30+
31+
}
32+
33+
public static Map<Boolean, List<Integer>> partitionPrimes(int n) {
34+
return IntStream.rangeClosed(2, n).boxed()
35+
.collect(partitioningBy(PartitionPrimeNumbers::isPrime));
36+
}
37+
38+
public static boolean isPrime(int candidate) {
39+
return IntStream.rangeClosed(2, candidate - 1)
40+
.limit((long) Math.floor(Math.sqrt((double) candidate)) - 1)
41+
.noneMatch(i -> candidate % i == 0);
42+
}
43+
44+
public static Map<Boolean, List<Integer>> partitionPrimesWithCustomCollector(int n) {
45+
return IntStream.rangeClosed(2, n).boxed().collect(new PrimeNumbersCollector());
46+
}
47+
48+
public static boolean isPrime(List<Integer> primes, Integer candidate) {
49+
double candidateRoot = Math.sqrt((double) candidate);
50+
//return primes.stream().filter(p -> p < candidateRoot).noneMatch(p -> candidate % p == 0);
51+
return takeWhile(primes, i -> i <= candidateRoot).stream().noneMatch(i -> candidate % i == 0);
52+
}
53+
54+
public static <A> List<A> takeWhile(List<A> list, Predicate<A> p) {
55+
int i = 0;
56+
for (A item : list) {
57+
if (!p.test(item)) {
58+
return list.subList(0, i);
59+
}
60+
i++;
61+
}
62+
return list;
63+
}
64+
65+
public static class PrimeNumbersCollector
66+
implements Collector<Integer, Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> {
67+
68+
@Override
69+
public Supplier<Map<Boolean, List<Integer>>> supplier() {
70+
return () -> new HashMap<Boolean, List<Integer>>() {{
71+
put(true, new ArrayList<Integer>());
72+
put(false, new ArrayList<Integer>());
73+
}};
74+
}
75+
76+
@Override
77+
public BiConsumer<Map<Boolean, List<Integer>>, Integer> accumulator() {
78+
return (Map<Boolean, List<Integer>> acc, Integer candidate) -> {
79+
acc.get(isPrime(acc.get(true),
80+
candidate))
81+
.add(candidate);
82+
};
83+
}
84+
85+
@Override
86+
public BinaryOperator<Map<Boolean, List<Integer>>> combiner() {
87+
return (Map<Boolean, List<Integer>> map1, Map<Boolean, List<Integer>> map2) -> {
88+
map1.get(true).addAll(map2.get(true));
89+
map1.get(false).addAll(map2.get(false));
90+
return map1;
91+
};
92+
}
93+
94+
@Override
95+
public Function<Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> finisher() {
96+
return i -> i;
97+
}
98+
99+
@Override
100+
public Set<Characteristics> characteristics() {
101+
return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH));
102+
}
103+
}
104+
105+
public Map<Boolean, List<Integer>> partitionPrimesWithInlineCollector(int n) {
106+
return Stream.iterate(2, i -> i + 1).limit(n)
107+
.collect(
108+
() -> new HashMap<Boolean, List<Integer>>() {{
109+
put(true, new ArrayList<Integer>());
110+
put(false, new ArrayList<Integer>());
111+
}},
112+
(acc, candidate) -> {
113+
acc.get(isPrime(acc.get(true), candidate))
114+
.add(candidate);
115+
},
116+
(map1, map2) -> {
117+
map1.get(true).addAll(map2.get(true));
118+
map1.get(false).addAll(map2.get(false));
119+
});
120+
}
121+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static com.brianway.learning.java8.streamapi.Dish.menu;
4+
import static java.util.stream.Collectors.reducing;
5+
6+
public class Reducing {
7+
8+
public static void main(String... args) {
9+
System.out.println("Total calories in menu: " + calculateTotalCalories());
10+
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithMethodReference());
11+
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithoutCollectors());
12+
System.out.println("Total calories in menu: " + calculateTotalCaloriesUsingSum());
13+
}
14+
15+
private static int calculateTotalCalories() {
16+
return menu.stream().collect(reducing(0, Dish::getCalories, (Integer i, Integer j) -> i + j));
17+
}
18+
19+
private static int calculateTotalCaloriesWithMethodReference() {
20+
return menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
21+
}
22+
23+
private static int calculateTotalCaloriesWithoutCollectors() {
24+
return menu.stream().map(Dish::getCalories).reduce(Integer::sum).get();
25+
}
26+
27+
private static int calculateTotalCaloriesUsingSum() {
28+
return menu.stream().mapToInt(Dish::getCalories).sum();
29+
}
30+
}

java8/src/main/java/com/brianway/learning/java8/streamapi/StreamBasic.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import java.util.Comparator;
99
import java.util.List;
1010

11+
/**
12+
* 指令式和函数式分别挑选低热量食物名
13+
*/
1114
public class StreamBasic {
1215

1316
public static void main(String... args) {

0 commit comments

Comments
 (0)