Skip to content

Commit dec2180

Browse files
committed
[add] add Stream API examples
1 parent 2bd399c commit dec2180

File tree

9 files changed

+424
-0
lines changed

9 files changed

+424
-0
lines changed

java8/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Java 8 新特性
2+
3+
《Java 8 In Action》一书
4+
5+
源码参考了 **java8/Java8InAction**:[https://github.com/java8/Java8InAction](https://github.com/java8/Java8InAction)
6+
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import java.nio.charset.Charset;
4+
import java.nio.file.Files;
5+
import java.nio.file.Paths;
6+
import java.util.Arrays;
7+
import java.util.function.IntSupplier;
8+
import java.util.stream.IntStream;
9+
import java.util.stream.Stream;
10+
11+
public class BuildingStreams {
12+
13+
public static void main(String... args) throws Exception {
14+
15+
// Stream.of
16+
Stream<String> stream = Stream.of("Java 8", "Lambdas", "In", "Action");
17+
stream.map(String::toUpperCase).forEach(System.out::println);
18+
19+
// Stream.empty
20+
Stream<String> emptyStream = Stream.empty();
21+
22+
// Arrays.stream
23+
int[] numbers = {2, 3, 5, 7, 11, 13};
24+
System.out.println(Arrays.stream(numbers).sum());
25+
26+
// Stream.iterate
27+
Stream.iterate(0, n -> n + 2)
28+
.limit(10)
29+
.forEach(System.out::println);
30+
31+
// fibonnaci with iterate
32+
Stream.iterate(new int[] {0, 1}, t -> new int[] {t[1], t[0] + t[1]})
33+
.limit(10)
34+
.forEach(t -> System.out.println("(" + t[0] + ", " + t[1] + ")"));
35+
36+
Stream.iterate(new int[] {0, 1}, t -> new int[] {t[1], t[0] + t[1]})
37+
.limit(10)
38+
.map(t -> t[0])
39+
.forEach(System.out::println);
40+
41+
// random stream of doubles with Stream.generate
42+
Stream.generate(Math::random)
43+
.limit(10)
44+
.forEach(System.out::println);
45+
46+
// stream of 1s with Stream.generate
47+
IntStream.generate(() -> 1)
48+
.limit(5)
49+
.forEach(System.out::println);
50+
51+
IntStream.generate(new IntSupplier() {
52+
public int getAsInt() {
53+
return 2;
54+
}
55+
}).limit(5)
56+
.forEach(System.out::println);
57+
58+
IntSupplier fib = new IntSupplier() {
59+
private int previous = 0;
60+
private int current = 1;
61+
62+
public int getAsInt() {
63+
int nextValue = this.previous + this.current;
64+
this.previous = this.current;
65+
this.current = nextValue;
66+
return this.previous;
67+
}
68+
};
69+
IntStream.generate(fib).limit(10).forEach(System.out::println);
70+
71+
String path = BuildingStreams.class.getResource("/").getPath() + "/data-building.txt";
72+
long uniqueWords = Files.lines(Paths.get(path), Charset.defaultCharset())
73+
.flatMap(line -> Arrays.stream(line.split(" ")))
74+
.distinct()
75+
.count();
76+
77+
System.out.println("There are " + uniqueWords + " unique words in data.txt");
78+
79+
}
80+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
public class Dish {
7+
8+
private final String name;
9+
private final boolean vegetarian;
10+
private final int calories;
11+
private final Type type;
12+
13+
public Dish(String name, boolean vegetarian, int calories, Type type) {
14+
this.name = name;
15+
this.vegetarian = vegetarian;
16+
this.calories = calories;
17+
this.type = type;
18+
}
19+
20+
public String getName() {
21+
return name;
22+
}
23+
24+
public boolean isVegetarian() {
25+
return vegetarian;
26+
}
27+
28+
public int getCalories() {
29+
return calories;
30+
}
31+
32+
public Type getType() {
33+
return type;
34+
}
35+
36+
public enum Type {
37+
MEAT,
38+
FISH,
39+
OTHER
40+
}
41+
42+
@Override
43+
public String toString() {
44+
return name;
45+
}
46+
47+
public static final List<Dish> menu =
48+
Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
49+
new Dish("beef", false, 700, Dish.Type.MEAT),
50+
new Dish("chicken", false, 400, Dish.Type.MEAT),
51+
new Dish("french fries", true, 530, Dish.Type.OTHER),
52+
new Dish("rice", true, 350, Dish.Type.OTHER),
53+
new Dish("season fruit", true, 120, Dish.Type.OTHER),
54+
new Dish("pizza", true, 550, Dish.Type.OTHER),
55+
new Dish("prawns", false, 400, Dish.Type.FISH),
56+
new Dish("salmon", false, 450, Dish.Type.FISH));
57+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static java.util.stream.Collectors.groupingBy;
4+
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
import java.util.HashMap;
8+
import java.util.List;
9+
import java.util.Map;
10+
11+
public class GroupingTransactions {
12+
13+
public static List<Transaction> transactions = Arrays.asList(
14+
new Transaction(Currency.EUR, 1500.0),
15+
new Transaction(Currency.USD, 2300.0),
16+
new Transaction(Currency.GBP, 9900.0),
17+
new Transaction(Currency.EUR, 1100.0),
18+
new Transaction(Currency.JPY, 7800.0),
19+
new Transaction(Currency.CHF, 6700.0),
20+
new Transaction(Currency.EUR, 5600.0),
21+
new Transaction(Currency.USD, 4500.0),
22+
new Transaction(Currency.CHF, 3400.0),
23+
new Transaction(Currency.GBP, 3200.0),
24+
new Transaction(Currency.USD, 4600.0),
25+
new Transaction(Currency.JPY, 5700.0),
26+
new Transaction(Currency.EUR, 6800.0));
27+
28+
public static void main(String... args) {
29+
groupImperatively();
30+
groupFunctionally();
31+
32+
}
33+
34+
private static void groupImperatively() {
35+
Map<Currency, List<Transaction>> transactionsByCurrencies = new HashMap<>();
36+
for (Transaction transaction : transactions) {
37+
Currency currency = transaction.getCurrency();
38+
List<Transaction> transactionsForCurrency = transactionsByCurrencies.get(currency);
39+
if (transactionsForCurrency == null) {
40+
transactionsForCurrency = new ArrayList<>();
41+
transactionsByCurrencies.put(currency, transactionsForCurrency);
42+
}
43+
transactionsForCurrency.add(transaction);
44+
}
45+
46+
System.out.println(transactionsByCurrencies);
47+
}
48+
49+
private static void groupFunctionally() {
50+
Map<Currency, List<Transaction>> transactionsByCurrencies = transactions.stream().collect(groupingBy(Transaction::getCurrency));
51+
System.out.println(transactionsByCurrencies);
52+
}
53+
54+
public static class Transaction {
55+
private final Currency currency;
56+
private final double value;
57+
58+
public Transaction(Currency currency, double value) {
59+
this.currency = currency;
60+
this.value = value;
61+
}
62+
63+
public Currency getCurrency() {
64+
return currency;
65+
}
66+
67+
public double getValue() {
68+
return value;
69+
}
70+
71+
@Override
72+
public String toString() {
73+
return currency + " " + value;
74+
}
75+
}
76+
77+
public enum Currency {
78+
EUR,
79+
USD,
80+
JPY,
81+
GBP,
82+
CHF
83+
}
84+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static java.util.Comparator.comparing;
4+
import static java.util.stream.Collectors.toList;
5+
6+
import java.util.Arrays;
7+
import java.util.List;
8+
9+
public class PuttingIntoPractice {
10+
public static void main(String... args) {
11+
Trader raoul = new Trader("Raoul", "Cambridge");
12+
Trader mario = new Trader("Mario", "Milan");
13+
Trader alan = new Trader("Alan", "Cambridge");
14+
Trader brian = new Trader("Brian", "Cambridge");
15+
16+
List<Transaction> transactions = Arrays.asList(
17+
new Transaction(brian, 2011, 300),
18+
new Transaction(raoul, 2012, 1000),
19+
new Transaction(raoul, 2011, 400),
20+
new Transaction(mario, 2012, 710),
21+
new Transaction(mario, 2012, 700),
22+
new Transaction(alan, 2012, 950)
23+
);
24+
25+
// Query 1: Find all transactions from year 2011 and sort them by value (small to high).
26+
List<Transaction> tr2011 = transactions.stream()
27+
.filter(transaction -> transaction.getYear() == 2011)
28+
.sorted(comparing(Transaction::getValue))
29+
.collect(toList());
30+
System.out.println(tr2011);
31+
32+
// Query 2: What are all the unique cities where the traders work?
33+
List<String> cities =
34+
transactions.stream()
35+
.map(transaction -> transaction.getTrader().getCity())
36+
.distinct()
37+
.collect(toList());
38+
System.out.println(cities);
39+
40+
// Query 3: Find all traders from Cambridge and sort them by name.
41+
42+
List<Trader> traders =
43+
transactions.stream()
44+
.map(Transaction::getTrader)
45+
.filter(trader -> trader.getCity().equals("Cambridge"))
46+
.distinct()
47+
.sorted(comparing(Trader::getName))
48+
.collect(toList());
49+
System.out.println(traders);
50+
51+
// Query 4: Return a string of all traders’ names sorted alphabetically.
52+
53+
String traderStr =
54+
transactions.stream()
55+
.map(transaction -> transaction.getTrader().getName())
56+
.distinct()
57+
.sorted()
58+
.reduce("", (n1, n2) -> n1 + n2);
59+
System.out.println(traderStr);
60+
61+
// Query 5: Are there any trader based in Milan?
62+
63+
boolean milanBased =
64+
transactions.stream()
65+
.anyMatch(transaction -> transaction.getTrader()
66+
.getCity()
67+
.equals("Milan")
68+
);
69+
System.out.println(milanBased);
70+
71+
// Query 6: Update all transactions so that the traders from Milan are set to Cambridge.
72+
transactions.stream()
73+
.map(Transaction::getTrader)
74+
.filter(trader -> trader.getCity().equals("Milan"))
75+
.forEach(trader -> trader.setCity("Cambridge"));
76+
System.out.println(transactions);
77+
78+
// Query 7: What's the highest value in all the transactions?
79+
int highestValue =
80+
transactions.stream()
81+
.map(Transaction::getValue)
82+
.reduce(0, Integer::max);
83+
System.out.println(highestValue);
84+
}
85+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static java.util.Comparator.comparing;
4+
import static java.util.stream.Collectors.toList;
5+
6+
import java.util.ArrayList;
7+
import java.util.Collections;
8+
import java.util.Comparator;
9+
import java.util.List;
10+
11+
public class StreamBasic {
12+
13+
public static void main(String... args) {
14+
// Java 7
15+
getLowCaloricDishesNamesInJava7(Dish.menu).forEach(System.out::println);
16+
17+
System.out.println("---");
18+
19+
// Java 8
20+
getLowCaloricDishesNamesInJava8(Dish.menu).forEach(System.out::println);
21+
22+
}
23+
24+
public static List<String> getLowCaloricDishesNamesInJava7(List<Dish> dishes) {
25+
List<Dish> lowCaloricDishes = new ArrayList<>();
26+
for (Dish d : dishes) {
27+
if (d.getCalories() < 400) {
28+
lowCaloricDishes.add(d);
29+
}
30+
}
31+
List<String> lowCaloricDishesName = new ArrayList<>();
32+
Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
33+
public int compare(Dish d1, Dish d2) {
34+
return Integer.compare(d1.getCalories(), d2.getCalories());
35+
}
36+
});
37+
for (Dish d : lowCaloricDishes) {
38+
lowCaloricDishesName.add(d.getName());
39+
}
40+
return lowCaloricDishesName;
41+
}
42+
43+
public static List<String> getLowCaloricDishesNamesInJava8(List<Dish> dishes) {
44+
return dishes.stream()
45+
.filter(d -> d.getCalories() < 400)
46+
.sorted(comparing(Dish::getCalories))
47+
.map(Dish::getName)
48+
.collect(toList());
49+
}
50+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
public class Trader {
4+
5+
private String name;
6+
private String city;
7+
8+
public Trader(String n, String c) {
9+
this.name = n;
10+
this.city = c;
11+
}
12+
13+
public String getName() {
14+
return this.name;
15+
}
16+
17+
public String getCity() {
18+
return this.city;
19+
}
20+
21+
public void setCity(String newCity) {
22+
this.city = newCity;
23+
}
24+
25+
public String toString() {
26+
return "Trader:" + this.name + " in " + this.city;
27+
}
28+
}

0 commit comments

Comments
 (0)