Skip to content

Commit 019232f

Browse files
committed
第5章示例代码
1 parent bbb8dd6 commit 019232f

File tree

10 files changed

+471
-0
lines changed

10 files changed

+471
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package com.wbs.java8lambda.chapter5;
2+
3+
import java.io.IOException;
4+
import java.nio.charset.Charset;
5+
import java.nio.file.Files;
6+
import java.nio.file.Paths;
7+
import java.util.Arrays;
8+
import java.util.function.IntSupplier;
9+
import java.util.stream.IntStream;
10+
import java.util.stream.Stream;
11+
12+
/**
13+
* TODO
14+
*
15+
* @author: wangbingshuai
16+
* @create: 2019-10-31 20:06
17+
**/
18+
public class BuildingStreams {
19+
public static void main(String[] args) throws IOException {
20+
Stream<String> stream = Stream.of("Java 8", "Lambdas", "In", "Action");
21+
stream.map(String::toUpperCase).forEach(System.out::println);
22+
23+
Stream<Object> emptyStream = Stream.empty();
24+
25+
System.out.println("---");
26+
27+
int[] numbers = {2, 3, 5, 7, 11, 13};
28+
System.out.println(Arrays.stream(numbers).sum());
29+
30+
System.out.println("---");
31+
32+
Stream.iterate(0, n -> n + 2)
33+
.limit(10)
34+
.forEach(System.out::println);
35+
36+
System.out.println("---");
37+
38+
Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
39+
.limit(10)
40+
.forEach(t -> System.out.println("(" + t[0] + ", " + t[1] + ")"));
41+
42+
System.out.println("---");
43+
44+
Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
45+
.limit(10)
46+
.map(t -> t[0])
47+
.forEach(System.out::println);
48+
49+
System.out.println("---");
50+
51+
Stream.generate(Math::random)
52+
.limit(5)
53+
.forEach(System.out::println);
54+
55+
System.out.println("---");
56+
57+
IntStream.generate(() -> 1)
58+
.limit(5)
59+
.forEach(System.out::println);
60+
61+
System.out.println("---");
62+
63+
IntStream.generate(new IntSupplier() {
64+
@Override
65+
public int getAsInt() {
66+
return 2;
67+
}
68+
}).limit(5)
69+
.forEach(System.out::println);
70+
71+
System.out.println("---");
72+
73+
IntSupplier fib = new IntSupplier() {
74+
private int previous = 0;
75+
private int current = 1;
76+
77+
@Override
78+
public int getAsInt() {
79+
int nextValue = this.previous + this.current;
80+
this.previous = this.current;
81+
this.current = nextValue;
82+
return this.previous;
83+
}
84+
};
85+
IntStream.generate(fib).limit(10).forEach(System.out::println);
86+
87+
System.out.println("---");
88+
89+
long uniqueWords = Files.lines(Paths.get("/Users/wangbingshuai/MyOwnProject/java8-lambda/src/main/resources/lambdasinaction/chap5/data.txt"), Charset.defaultCharset())
90+
.flatMap(line -> Arrays.stream(line.split(" ")))
91+
.distinct()
92+
.count();
93+
System.out.println("There are " + uniqueWords + " unique words in data.txt");
94+
}
95+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.wbs.java8lambda.chapter5;
2+
3+
import com.wbs.java8lambda.chapter4.Dish;
4+
5+
import java.util.Arrays;
6+
import java.util.List;
7+
import java.util.stream.Collectors;
8+
9+
/**
10+
* TODO
11+
*
12+
* @author: wangbingshuai
13+
* @create: 2019-10-31 19:33
14+
**/
15+
public class Filtering {
16+
public static void main(String[] args) {
17+
List<Dish> vegetarianMenu = Dish.menu.stream()
18+
.filter(Dish::getVegetarian)
19+
.collect(Collectors.toList());
20+
vegetarianMenu.forEach(System.out::println);
21+
22+
System.out.println("---");
23+
24+
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
25+
numbers.stream()
26+
.filter(n -> n % 2 == 0)
27+
.distinct()
28+
.forEach(System.out::println);
29+
30+
System.out.println("---");
31+
32+
List<Dish> dishesLimit3 = Dish.menu.stream()
33+
.filter(d -> d.getCalories() > 300)
34+
.limit(3)
35+
.collect(Collectors.toList());
36+
dishesLimit3.forEach(System.out::println);
37+
38+
System.out.println("---");
39+
40+
List<Dish> dishesSkip2 = Dish.menu.stream()
41+
.filter(d -> d.getCalories() > 300)
42+
.skip(2)
43+
.collect(Collectors.toList());
44+
dishesSkip2.forEach(System.out::println);
45+
}
46+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.wbs.java8lambda.chapter5;
2+
3+
import com.wbs.java8lambda.chapter4.Dish;
4+
5+
import java.util.Optional;
6+
7+
/**
8+
* TODO
9+
*
10+
* @author: wangbingshuai
11+
* @create: 2019-10-31 19:53
12+
**/
13+
public class Finding {
14+
public static void main(String[] args) {
15+
if (isVegetarianFriendMenu()) {
16+
System.out.println("Vegetarian friendly");
17+
}
18+
19+
System.out.println(isHealthyMenu());
20+
System.out.println(isHealthyMenu2());
21+
22+
Optional<Dish> dish = findVegetarianDish();
23+
dish.ifPresent(d -> System.out.println(d.getName()));
24+
}
25+
26+
private static boolean isVegetarianFriendMenu() {
27+
return Dish.menu.stream().allMatch(Dish::getVegetarian);
28+
}
29+
30+
private static boolean isHealthyMenu() {
31+
return Dish.menu.stream().allMatch(d -> d.getCalories() < 1000);
32+
}
33+
34+
private static boolean isHealthyMenu2() {
35+
return Dish.menu.stream().noneMatch(d -> d.getCalories() >= 1000);
36+
}
37+
38+
private static Optional<Dish> findVegetarianDish() {
39+
return Dish.menu.stream().filter(Dish::getVegetarian).findAny();
40+
}
41+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.wbs.java8lambda.chapter5;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
import java.util.stream.Collectors;
6+
7+
/**
8+
* TODO
9+
*
10+
* @author: wangbingshuai
11+
* @create: 2019-10-31 20:02
12+
**/
13+
public class Laziness {
14+
public static void main(String[] args) {
15+
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
16+
List<Integer> twoEvenSquares = numbers.stream()
17+
.filter(n -> {
18+
System.out.println("filtering " + n);
19+
return n % 2 == 0;
20+
})
21+
.map(n -> {
22+
System.out.println("mapping " + n);
23+
return n * n;
24+
})
25+
.limit(2)
26+
.collect(Collectors.toList());
27+
System.out.println(twoEvenSquares);
28+
}
29+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.wbs.java8lambda.chapter5;
2+
3+
import com.wbs.java8lambda.chapter4.Dish;
4+
5+
import java.util.Arrays;
6+
import java.util.List;
7+
import java.util.stream.Collectors;
8+
9+
/**
10+
* TODO
11+
*
12+
* @author: wangbingshuai
13+
* @create: 2019-10-31 19:41
14+
**/
15+
public class Mapping {
16+
public static void main(String[] args) {
17+
List<String> dishNames = Dish.menu.stream()
18+
.map(Dish::getName)
19+
.collect(Collectors.toList());
20+
System.out.println(dishNames);
21+
22+
System.out.println("---");
23+
24+
List<String> words = Arrays.asList("Hello", "World");
25+
List<Integer> wordLengths = words.stream()
26+
.map(String::length)
27+
.collect(Collectors.toList());
28+
System.out.println(wordLengths);
29+
30+
System.out.println("---");
31+
32+
words.stream()
33+
.flatMap(line -> Arrays.stream(line.split("")))
34+
.distinct()
35+
.forEach(System.out::println);
36+
37+
System.out.println("---");
38+
39+
List<Integer> numbers1 = Arrays.asList(1, 2, 3, 4, 5);
40+
List<Integer> numbers2 = Arrays.asList(6, 7, 8);
41+
List<int[]> pairs = numbers1.stream()
42+
.flatMap(i -> numbers2.stream().map(j -> new int[]{i, j}))
43+
.filter(pair -> (pair[0] + pair[1]) % 3 == 0)
44+
.collect(Collectors.toList());
45+
pairs.forEach(pair -> System.out.println("(" + pair[0] + ", " + pair[1] + ")"));
46+
}
47+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.wbs.java8lambda.chapter5;
2+
3+
import com.wbs.java8lambda.chapter4.Dish;
4+
5+
import java.util.Arrays;
6+
import java.util.List;
7+
import java.util.OptionalInt;
8+
import java.util.stream.IntStream;
9+
import java.util.stream.Stream;
10+
11+
/**
12+
* TODO
13+
*
14+
* @author: wangbingshuai
15+
* @create: 2019-11-01 16:07
16+
**/
17+
public class NumericStreams {
18+
public static void main(String[] args) {
19+
List<Integer> numbers = Arrays.asList(3, 4, 5, 1, 2);
20+
Arrays.stream(numbers.toArray()).forEach(System.out::println);
21+
22+
int calories = Dish.menu.stream()
23+
.mapToInt(Dish::getCalories)
24+
.sum();
25+
System.out.println("Number of calories:" + calories);
26+
27+
OptionalInt maxCalories = Dish.menu.stream()
28+
.mapToInt(Dish::getCalories)
29+
.max();
30+
int max;
31+
if (maxCalories.isPresent()) {
32+
max = maxCalories.getAsInt();
33+
} else {
34+
max = 1;
35+
}
36+
System.out.println(max);
37+
38+
IntStream evenNumbers = IntStream.rangeClosed(1, 100)
39+
.filter(n -> n % 2 == 0);
40+
System.out.println(evenNumbers.count());
41+
42+
Stream<int[]> pythagoreanTriples = IntStream.rangeClosed(1, 100).boxed()
43+
.flatMap(a -> IntStream.rangeClosed(a, 100)
44+
.filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
45+
.boxed()
46+
.map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)}));
47+
pythagoreanTriples.forEach(t -> System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
48+
}
49+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package com.wbs.java8lambda.chapter5;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
import static java.util.Comparator.comparing;
7+
import static java.util.stream.Collectors.toList;
8+
9+
/**
10+
* TODO
11+
*
12+
* @author: wangbingshuai
13+
* @create: 2019-11-01 16:18
14+
**/
15+
public class PuttingIntoPractice {
16+
public static void main(String[] args) {
17+
Trader raoul = new Trader("Raoul", "Cambridge");
18+
Trader mario = new Trader("Mario", "Milan");
19+
Trader alan = new Trader("Alan", "Cambridge");
20+
Trader brian = new Trader("Brian", "Cambridge");
21+
22+
List<Transaction> transactions = Arrays.asList(
23+
new Transaction(brian, 2011, 300),
24+
new Transaction(raoul, 2012, 1000),
25+
new Transaction(raoul, 2011, 400),
26+
new Transaction(mario, 2012, 710),
27+
new Transaction(mario, 2012, 700),
28+
new Transaction(alan, 2012, 950)
29+
);
30+
31+
// Query 1: Find all transactions from year 2011 and sort them by value (small to high).
32+
List<Transaction> tr2011 = transactions.stream()
33+
.filter(transaction -> transaction.getYear() == 2011)
34+
.sorted(comparing(Transaction::getValue))
35+
.collect(toList());
36+
System.out.println(tr2011);
37+
38+
// Query 2: What are all the unique cities where the traders work?
39+
List<String> cities = transactions.stream()
40+
.map(transaction -> transaction.getTrader().getCity())
41+
.distinct()
42+
.collect(toList());
43+
System.out.println(cities);
44+
45+
// Query 3: Find all traders from Cambridge and sort them by name.
46+
List<Trader> traders = transactions.stream()
47+
.map(Transaction::getTrader)
48+
.filter(trader -> trader.getCity().equals("Cambridge"))
49+
.distinct()
50+
.sorted(comparing(Trader::getName))
51+
.collect(toList());
52+
System.out.println(traders);
53+
54+
// Query 4: Return a string of all traders’ names sorted alphabetically.
55+
String traderStr = transactions.stream()
56+
.map(transaction -> transaction.getTrader().getName())
57+
.distinct()
58+
.sorted()
59+
.reduce("", (n1, n2) -> n1 + n2);
60+
System.out.println(traderStr);
61+
62+
// Query 5: Are there any trader based in Milan?
63+
boolean milanBased = transactions.stream()
64+
.anyMatch(transaction -> transaction.getTrader().getCity().equals("Milan"));
65+
System.out.println(milanBased);
66+
67+
// Query 6: Update all transactions so that the traders from Milan are set to Cambridge.
68+
transactions.stream()
69+
.map(Transaction::getTrader)
70+
.filter(trader -> trader.getCity().equals("Milan"))
71+
.forEach(trader -> trader.setCity("Cambridge"));
72+
System.out.println(transactions);
73+
74+
// Query 7: What's the highest value in all the transactions?
75+
int highestValue =
76+
transactions.stream()
77+
.map(Transaction::getValue)
78+
.reduce(0, Integer::max);
79+
System.out.println(highestValue);
80+
}
81+
}

0 commit comments

Comments
 (0)