Skip to content

Commit 9835081

Browse files
author
alexVengrovsk
committed
Code for the article "Java 8 Stream API Tutorial"
alextrentton@gmail.com Signed-off-by: <alextrentton@gmail.com>
1 parent 7335ef2 commit 9835081

2 files changed

Lines changed: 320 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.streamApi;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
import java.util.stream.IntStream;
6+
import java.util.stream.Stream;
7+
8+
/**
9+
* Created by Alex Vengr
10+
*/
11+
public class Product {
12+
13+
private int price;
14+
15+
private String name;
16+
17+
private boolean utilize;
18+
19+
public Product(int price, String name) {
20+
this(price);
21+
this.name = name;
22+
}
23+
24+
public Product(int price) {
25+
this.price = price;
26+
}
27+
28+
public Product() {
29+
}
30+
31+
public int getPrice() {
32+
return price;
33+
}
34+
35+
public void setPrice(int price) {
36+
this.price = price;
37+
}
38+
39+
public String getName() {
40+
return name;
41+
}
42+
43+
public void setName(String name) {
44+
this.name = name;
45+
}
46+
47+
48+
public static Stream<String> streamOf(List<String> list) {
49+
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
50+
}
51+
}
Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
package com.baeldung.java8;
2+
3+
import com.baeldung.streamApi.Product;
4+
import org.junit.Before;
5+
import org.junit.BeforeClass;
6+
import org.junit.Test;
7+
import org.mockito.Mock;
8+
import org.mockito.Mockito;
9+
10+
import java.io.BufferedWriter;
11+
import java.io.File;
12+
import java.io.IOException;
13+
import java.nio.charset.Charset;
14+
import java.nio.file.Files;
15+
import java.nio.file.Path;
16+
import java.nio.file.Paths;
17+
import java.util.*;
18+
import java.util.logging.Logger;
19+
import java.util.regex.Pattern;
20+
import java.util.stream.*;
21+
22+
import static org.junit.Assert.*;
23+
import static org.mockito.Matchers.anyString;
24+
import static org.mockito.Mockito.mock;
25+
26+
/**
27+
* Created by Alex Vengr
28+
*/
29+
public class Java8StreamApiTest {
30+
31+
private long counter;
32+
33+
private static Logger log = Logger.getAnonymousLogger();
34+
35+
private List<Product> productList;
36+
37+
38+
@Before
39+
public void init() {
40+
productList = Arrays.asList(new Product(23, "potatoes"),
41+
new Product(14, "orange"), new Product(13, "lemon"),
42+
new Product(23, "bread"), new Product(13, "sugar"));
43+
}
44+
45+
@Test
46+
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
47+
48+
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
49+
long size = list.stream().skip(1)
50+
.map(element -> element.substring(0, 3)).count();
51+
assertEquals(list.size() - 1, size);
52+
}
53+
54+
@Test
55+
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
56+
57+
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
58+
59+
counter = 0;
60+
long sizeFirst = list.stream()
61+
.skip(2).map(element -> {
62+
wasCalled();
63+
return element.substring(0, 3);
64+
}).count();
65+
assertEquals( 1, counter);
66+
67+
counter = 0;
68+
long sizeSecond = list.stream().map(element -> {
69+
wasCalled();
70+
return element.substring(0, 3);
71+
}).skip(2).count();
72+
assertEquals( 3, counter);
73+
}
74+
75+
@Test
76+
public void createEmptyStream_whenEmpty_thenCorrect() {
77+
78+
Stream<String> streamEmpty = Stream.empty();
79+
assertEquals(0, streamEmpty.count());
80+
81+
List<String> names = Collections.emptyList();
82+
Stream<String> streamOf = Product.streamOf(names);
83+
assertTrue(streamOf.count() == 0);
84+
}
85+
86+
@Test
87+
public void createStream_whenCreated_thenCorrect() {
88+
89+
Collection<String> collection = Arrays.asList("a", "b", "c");
90+
Stream<String> streamOfCollection = collection.stream();
91+
assertEquals(3, streamOfCollection.count());
92+
93+
Stream<String> streamOfArray = Stream.of("a", "b", "c");
94+
assertEquals(3, streamOfArray.count());
95+
96+
String[] arr = new String[]{"a", "b", "c"};
97+
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
98+
assertEquals(2, streamOfArrayPart.count());
99+
100+
IntStream intStream = IntStream.range(1, 3);
101+
LongStream longStream = LongStream.rangeClosed(1, 3);
102+
Random random = new Random();
103+
DoubleStream doubleStream = random.doubles(3);
104+
assertEquals(2, intStream.count());
105+
assertEquals(3, longStream.count());
106+
assertEquals(3, doubleStream.count());
107+
108+
IntStream streamOfChars = "abc".chars();
109+
IntStream str = "".chars();
110+
assertEquals(3, streamOfChars.count());
111+
112+
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
113+
assertEquals("a", streamOfString.findFirst().get());
114+
115+
Path path = getPath();
116+
Stream<String> streamOfStrings = null;
117+
try {
118+
streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
119+
} catch (IOException e) {
120+
e.printStackTrace();
121+
}
122+
assertEquals("a", streamOfStrings.findFirst().get());
123+
124+
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
125+
assertEquals(3, streamBuilder.count());
126+
127+
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
128+
assertEquals(10, streamGenerated.count());
129+
130+
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
131+
assertTrue(40 <= streamIterated.findAny().get());
132+
}
133+
134+
@Test
135+
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
136+
137+
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
138+
Optional<String> stream = list.stream()
139+
.filter(element -> {
140+
log.info("filter() was called");
141+
return element.contains("2");
142+
}).map(element -> {
143+
log.info("map() was called");
144+
return element.toUpperCase();
145+
}).findFirst();
146+
}
147+
148+
@Test
149+
public void reduce_whenExpected_thenCorrect() {
150+
151+
OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
152+
assertEquals(6, reduced.getAsInt());
153+
154+
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
155+
assertEquals(16, reducedTwoParams);
156+
157+
int reducedThreeParams = Stream.of(1, 2, 3)
158+
.reduce(10, (a, b) -> a + b, (a, b) -> {
159+
log.info("combiner was called");
160+
return a + b;
161+
});
162+
assertEquals(16, reducedThreeParams);
163+
164+
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
165+
.reduce(10, (a, b) -> a + b, (a, b) -> {
166+
log.info("combiner was called");
167+
return a + b;
168+
});
169+
assertEquals(36, reducedThreeParamsParallel);
170+
}
171+
172+
@Test
173+
public void collecting_whenAsExpected_thenCorrect() {
174+
175+
List<String> collectorCollection = productList.stream()
176+
.map(Product::getName).collect(Collectors.toList());
177+
178+
assertTrue(collectorCollection instanceof List);
179+
assertEquals(5, collectorCollection.size());
180+
181+
String listToString = productList.stream().map(Product::getName)
182+
.collect(Collectors.joining(", ", "[", "]"));
183+
184+
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
185+
186+
double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
187+
assertTrue(17.2 == averagePrice);
188+
189+
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
190+
assertEquals(86, summingPrice);
191+
192+
IntSummaryStatistics statistics = productList.stream()
193+
.collect(Collectors.summarizingInt(Product::getPrice));
194+
assertEquals(23, statistics.getMax());
195+
196+
Map<Integer, List<Product>> collectorMapOfLists = productList.stream()
197+
.collect(Collectors.groupingBy(Product::getPrice));
198+
assertEquals(3, collectorMapOfLists.keySet().size());
199+
200+
Map<Boolean, List<Product>> mapPartioned = productList.stream()
201+
.collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
202+
assertEquals(2, mapPartioned.keySet().size());
203+
204+
}
205+
206+
@Test(expected = UnsupportedOperationException.class)
207+
public void collect_whenThrows_thenCorrect() {
208+
Set<Product> unmodifiableSet = productList.stream()
209+
.collect(Collectors.collectingAndThen(Collectors.toSet(),
210+
Collections::unmodifiableSet));
211+
unmodifiableSet.add(new Product(4, "tea"));
212+
}
213+
214+
@Test
215+
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
216+
Collector<Product, ?, LinkedList<Product>> toLinkedList =
217+
Collector.of(LinkedList::new, LinkedList::add,
218+
(first, second) -> { first.addAll(second); return first; });
219+
220+
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
221+
assertTrue(linkedListOfPersons.containsAll(productList));
222+
}
223+
224+
@Test
225+
public void parallelStream_whenWorks_thenCorrect() {
226+
Stream<Product> streamOfCollection = productList.parallelStream();
227+
boolean isParallel = streamOfCollection.isParallel();
228+
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
229+
.anyMatch(price -> price > 200);
230+
assertTrue(isParallel && haveBigPrice);
231+
}
232+
233+
@Test
234+
public void parallel_whenIsParallel_thenCorrect() {
235+
IntStream intStreamParallel =
236+
IntStream.range(1, 150).parallel().map(element -> element * 34);
237+
boolean isParallel = intStreamParallel.isParallel();
238+
assertTrue(isParallel);
239+
}
240+
241+
@Test
242+
public void parallel_whenIsSequential_thenCorrect() {
243+
IntStream intStreamParallel =
244+
IntStream.range(1, 150).parallel().map(element -> element * 34);
245+
IntStream intStreamSequential = intStreamParallel.sequential();
246+
boolean isParallel = intStreamParallel.isParallel();
247+
assertFalse(isParallel);
248+
}
249+
250+
private Path getPath() {
251+
Path path = null;
252+
try {
253+
path = Files.createTempFile(null, ".txt");
254+
} catch (IOException e) {
255+
e.printStackTrace();
256+
}
257+
258+
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
259+
writer.write("a\nb\nc");
260+
} catch (IOException e) {
261+
e.printStackTrace();
262+
}
263+
return path;
264+
}
265+
266+
private void wasCalled() {
267+
counter++;
268+
}
269+
}

0 commit comments

Comments
 (0)