* BAEL-1375 Counter in Java.

* BAEL-1375 Frequency counter in java.

* BAEL-1375 Refactored method names.

* BAEL-1375 refactored code.

* BAEL-1375 Fixed the test

* BAEL-1375 updated code to include parallel stream.
This commit is contained in:
Muhammed Almas 2017-12-25 20:20:22 +05:30 committed by Grzegorz Piwowarek
parent 284eeb894f
commit 72854479e7
2 changed files with 26 additions and 5 deletions

View File

@ -2,6 +2,7 @@ package com.baeldung.counter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
@ -18,8 +19,18 @@ public class CounterStatistics {
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
private static final Map<String, Long> counterWithLongWrapperStreamMap = new HashMap<>();
static {
CounterUtil.COUNTRY_NAMES = new String[10000];
final String prefix = "NewString";
Random random = new Random();
for (int i=0; i<10000; i++) {
CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
}
}
@Benchmark
@Benchmark
public void wrapperAsCounter() {
CounterUtil.counterWithWrapperObject(counterMap);
}
@ -28,6 +39,11 @@ public class CounterStatistics {
public void lambdaExpressionWithWrapper() {
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
}
@Benchmark
public void parallelStreamWithWrapper() {
CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
}
@Benchmark
public void mutableIntegerAsCounter() {

View File

@ -6,7 +6,7 @@ import java.util.stream.Stream;
public class CounterUtil {
private final static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
for (String country : COUNTRY_NAMES) {
@ -15,9 +15,14 @@ public class CounterUtil {
}
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
counterMap.putAll(Stream.of(COUNTRY_NAMES)
Stream.of(COUNTRY_NAMES)
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
}
public static void counterWithParallelStreamAndWrapper(Map<String, Long> counterMap) {
Stream.of(COUNTRY_NAMES)
.parallel()
.collect(Collectors.groupingBy(k -> k, Collectors.counting())));
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
}
public static class MutableInteger {
@ -49,4 +54,4 @@ public class CounterUtil {
}
}
}
}