Skip to content

Commit 2639324

Browse files
sjmillingtonjzheaux
authored andcommitted
BAEL-2033 Stream Ordering (eugenp#4965)
1 parent e77e8c0 commit 2639324

3 files changed

Lines changed: 279 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.baeldung</groupId>
8+
<artifactId>StreamsOrdering</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<dependencies>
12+
<dependency>
13+
<groupId>junit</groupId>
14+
<artifactId>junit</artifactId>
15+
<version>4.12</version>
16+
<scope>test</scope>
17+
18+
</dependency>
19+
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
20+
<dependency>
21+
<groupId>org.openjdk.jmh</groupId>
22+
<artifactId>jmh-core</artifactId>
23+
<version>1.21</version>
24+
</dependency>
25+
26+
<dependency>
27+
<groupId>org.openjdk.jmh</groupId>
28+
<artifactId>jmh-generator-annprocess</artifactId>
29+
<version>1.21</version>
30+
<scope>provided</scope>
31+
</dependency>
32+
33+
</dependencies>
34+
</project>
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import org.junit.Before;
2+
import org.junit.Test;
3+
4+
import java.util.*;
5+
import java.util.function.Function;
6+
import java.util.logging.Level;
7+
import java.util.logging.Logger;
8+
import java.util.stream.Collectors;
9+
import java.util.stream.IntStream;
10+
11+
import static org.junit.Assert.assertEquals;
12+
13+
14+
public class StreamsOrderingTest {
15+
16+
Logger logger = Logger.getLogger( StreamsOrderingTest.class.getName());
17+
18+
@Before
19+
public void setUp() throws Exception {
20+
logger.setLevel(Level.ALL);
21+
}
22+
23+
@Test
24+
public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){
25+
26+
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
27+
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
28+
29+
Object[] listOutput = list.stream().toArray();
30+
Object[] setOutput = set.stream().toArray();
31+
32+
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
33+
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
34+
35+
}
36+
37+
@Test
38+
public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){
39+
40+
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
41+
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
42+
43+
Object[] listOutput = list.stream().parallel().toArray();
44+
Object[] setOutput = set.stream().parallel().toArray();
45+
46+
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
47+
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
48+
49+
}
50+
51+
52+
53+
@Test
54+
public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){
55+
Set<Integer> set = new TreeSet<>(
56+
Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230));
57+
58+
Object[] orderedArray = set.stream()
59+
.parallel()
60+
.limit(5)
61+
.toArray();
62+
Object[] unorderedArray = set.stream()
63+
.unordered()
64+
.parallel()
65+
.limit(5)
66+
.toArray();
67+
68+
logger.info(Arrays.toString(orderedArray));
69+
logger.info(Arrays.toString(unorderedArray));
70+
}
71+
72+
73+
@Test
74+
public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){
75+
76+
List<Integer> list = Arrays.asList(-3,10,-4,1,3);
77+
78+
Object[] listOutput = list.stream().toArray();
79+
Object[] listOutputSorted = list.stream().sorted().toArray();
80+
81+
assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput));
82+
assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted));
83+
84+
}
85+
86+
@Test
87+
public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){
88+
long start, end;
89+
start = System.currentTimeMillis();
90+
IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray();
91+
end = System.currentTimeMillis();
92+
System.out.println(String.format("Time taken when unordered: %d ms", (end - start)));
93+
}
94+
95+
96+
@Test
97+
public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){
98+
99+
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
100+
101+
list.stream().parallel().forEach(e -> logger.log(Level.INFO, e));
102+
list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e));
103+
104+
}
105+
106+
@Test
107+
public void givenSameCollection_whenStreamCollected_thenCheckOutput(){
108+
109+
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
110+
111+
List<String> collectionList = list.stream().parallel().collect(Collectors.toList());
112+
Set<String> collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new));
113+
114+
assertEquals("[B, A, C, D, F]", collectionList.toString());
115+
assertEquals("[A, B, C, D, F]", collectionSet.toString());
116+
117+
}
118+
119+
120+
@Test
121+
public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() {
122+
List<String> list = Arrays.asList("A", "BB", "CCC");
123+
124+
Map<String, Integer> hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
125+
126+
Object[] keySet = hashMap.keySet().toArray();
127+
128+
assertEquals("[BB, A, CCC]", Arrays.toString(keySet));
129+
130+
}
131+
132+
@Test
133+
public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() {
134+
List<String> list = Arrays.asList("A", "BB", "CCC", "CCC");
135+
136+
Map<String, Integer> linkedHashMap = list.stream().collect(Collectors.toMap(
137+
Function.identity(),
138+
String::length,
139+
(u, v) -> u,
140+
LinkedHashMap::new
141+
));
142+
143+
Object[] keySet = linkedHashMap.keySet().toArray();
144+
145+
assertEquals("[A, BB, CCC]", Arrays.toString(keySet));
146+
}
147+
148+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package benchmarking;
2+
3+
import org.junit.Test;
4+
import org.openjdk.jmh.annotations.*;
5+
import org.openjdk.jmh.infra.Blackhole;
6+
import org.openjdk.jmh.runner.Runner;
7+
import org.openjdk.jmh.runner.options.Options;
8+
import org.openjdk.jmh.runner.options.OptionsBuilder;
9+
import org.openjdk.jmh.runner.options.TimeValue;
10+
11+
import java.util.ArrayList;
12+
import java.util.List;
13+
import java.util.Random;
14+
import java.util.concurrent.TimeUnit;
15+
import java.util.stream.IntStream;
16+
17+
18+
public class TestBenchmark
19+
{
20+
21+
@Test
22+
public void
23+
launchBenchmark() throws Exception {
24+
25+
Options opt = new OptionsBuilder()
26+
// Specify which benchmarks to run.
27+
// You can be more specific if you'd like to run only one benchmark per test.
28+
.include(this.getClass().getName() + ".*")
29+
// Set the following options as needed
30+
.mode (Mode.AverageTime)
31+
.timeUnit(TimeUnit.MICROSECONDS)
32+
.warmupTime(TimeValue.seconds(1))
33+
.warmupIterations(2)
34+
.measurementTime(TimeValue.seconds(1))
35+
.measurementIterations(2)
36+
.threads(2)
37+
.forks(1)
38+
.shouldFailOnError(true)
39+
.shouldDoGC(true)
40+
//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
41+
//.addProfiler(WinPerfAsmProfiler.class)
42+
.build();
43+
44+
new Runner(opt).run();
45+
46+
47+
}
48+
49+
@Benchmark
50+
public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){
51+
IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray();
52+
}
53+
54+
@Benchmark
55+
public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){
56+
IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray();
57+
}
58+
59+
@Benchmark
60+
public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){
61+
IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray();
62+
}
63+
64+
@Benchmark
65+
public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() {
66+
//section 5.1.
67+
IntStream.range(1, 1_000_000).parallel().distinct().toArray();
68+
}
69+
70+
71+
// The JMH samples are the best documentation for how to use it
72+
// http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
73+
@State(Scope.Thread)
74+
public static class BenchmarkState
75+
{
76+
List<Integer> list;
77+
78+
@Setup(Level.Trial) public void
79+
initialize() {
80+
81+
Random rand = new Random();
82+
83+
list = new ArrayList<>();
84+
for (int i = 0; i < 1000; i++)
85+
list.add (rand.nextInt());
86+
}
87+
}
88+
89+
@Benchmark public void
90+
benchmark1 (BenchmarkState state, Blackhole bh) {
91+
92+
List<Integer> list = state.list;
93+
94+
for (int i = 0; i < 1000; i++)
95+
bh.consume (list.get (i));
96+
}
97+
}

0 commit comments

Comments
 (0)