BestAverage |
Tests |
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static double bestAverageGradeUsingMerge(String[][] data)> MapString,Long totalsMap = Arrays.stream(data).collect( > HashMap::new,> (m, i) - m.merge(i[0], Long.parseLong(i[1]), Long::sum), HashMap::putAll); MapString,Long countMap = Arrays.stream(data).collect(> Collectors.groupingBy((String[] a) - a[0], Collectors.counting()));> return totalsMap.entrySet().stream()> .map(e - e.getValue() / (double)countMap.get(e.getKey())) .reduce(Double::max).get(); } data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static double bestAverageGradeUsingList(String[][] data)> MapString, ListInteger totalsMap = Arrays.stream(data).collect(> HashMap::new,> (m, i) - m.computeIfAbsent(i[0], a - new ArrayList()).add(Integer.parseInt(i[1])),> HashMap::putAll);> double max = 0.0;> for(ListInteger list : totalsMap.values())> {> max = Math.max(max, list.stream().mapToInt(x - x).sum() / (double) list.size()); }> return max;>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static double bestAverageGradeUsingListAndReduce(String[][] data)> MapString, ListDouble totalsMap = Arrays.stream(data).collect(> HashMap::new,> (m, i) - m.computeIfAbsent(i[0], a - new ArrayList()).add(Double.parseDouble(i[1])),> HashMap::putAll);> return totalsMap.values().stream()> .map(a - a.stream().reduce(Double::sum).get() / a.size()) > .reduce(Double::max).get();>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static double bestAverageGradeUsingListAndSummaryStatistics(String[][] data)> MapString, ListInteger totalsMap = Arrays.stream(data).collect(> HashMap::new,> (m, i) - m.computeIfAbsent(i[0], a - new ArrayList()).add(Integer.parseInt(i[1])),> HashMap::putAll);> double maxAvg = 0.0;> for(ListInteger list : totalsMap.values())> {> IntSummaryStatistics stats = list.stream().mapToInt(x - x).summaryStatistics(); maxAvg = Math.max(maxAvg, stats.getAverage()); }> return maxAvg;>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static double bestAverageGradeUsingListAndAverage(String[][] data)> MapString, ListInteger totalsMap = Arrays.stream(data).collect(> HashMap::new,> (m, i) - m.computeIfAbsent(i[0], a - new ArrayList()).add(Integer.parseInt(i[1])),> HashMap::putAll);> return totalsMap.values().stream()> .map(a - a.stream().mapToDouble(x - x).average().getAsDouble()) > .reduce(Double::max).get();>} |
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass() String[][] data = { {"nick", "81"}, {"paul", "50"},> {"ron", "60"}, > {"nick", "100"}> };> boolean check = bestAverageGradeUsingMerge(data) == 90.5; > if(!check)> { return false; }> check = bestAverageGradeUsingList(data) == 90.5; if(!check)> {> return false;> } check = bestAverageGradeUsingListAndReduce(data) == 90.5;> if(!check) { return false;> }> check = bestAverageGradeUsingListAndSummaryStatistics(data) > if(!check)> {> return false; > } check = bestAverageGradeUsingListAndAverage(data) == 90.5;> if(!check) { return false;> }> return true; } |
ClassFactory
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>public class ClassFactorystatic abstract class Fruit{> int weight;> Fruit(int weight)> {> this.weight = weight;> }}> static class Apple extends Fruit> {> Apple(int weight)> { > super(weight);> }> {> return "Apple{}"; > }@Override> public String toString()}> static class Orange extends Fruit> {> Orange(int weight)> { > super(weight);> }> {> return "Orange{}";> }@Override> public String toString()}> static MapString,FunctionInteger, Fruit constructorMap = new HashMapString,FunctionInteger, Fruit() {{> put("apple", Apple::new); > put("orange", Orange::new);> }};> }>}static Fruit getFruit(String name, int weight){> return constructorMap.get(name).apply(weight); data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()Fruit apple = getFruit("apple", 50);boolean check = apple.toString().equals("Apple{}");> if(!check){return false;> }> Fruit orange = getFruit("orange", 50);> check = orange.toString().equals("Orange{}");> if(!check)> {> return false;> }return true;}
Conversions
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static ListInteger fromIntArrayToList(int[] a)> return Arrays.stream(a).boxed().collect(Collectors.toList()); >}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static SetInteger fromIntArrayToSet(int[] a)return Arrays.stream(a).boxed().collect(Collectors.toSet());>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static Integer[] fromIntToIntegerArray1(int[] a)return Arrays.stream(a).boxed().toArray(Integer[]::new);>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static Integer[] fromIntToIntegerArray2(int[] a)return IntStream.of(a).boxed().toArray(Integer[]::new);>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] fromIntegerToIntArray(Integer[] a)return Arrays.stream(a).mapToInt(x - x).toArray();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] fromListToIntArray(ListInteger list)> return list.stream().mapToInt(x - x).toArray();pre data-role="codeBlock" data-info="js" class="language-javascript">}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] flatten2DArray(int[][] a)return Arrays.stream(a).flatMapToInt(Arrays::stream).toArray();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static String[] fromIntToStringArray(int[] a)return Arrays.stream(a).mapToObj(String::valueOf).toArray(String[]::new);>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] fromStringToIntArray(String[] a)return Arrays.stream(a).mapToInt(Integer::valueOf).toArray();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] arrayOfConsecutiveInts(int start, int end)> return IntStream.rangeClosed(start, end).toArray();pre data-role="codeBlock" data-info="js" class="language-javascript">}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] arrayOfConsecutiveIntsReversed(int start, int end)> return IntStream.rangeClosed(start, end).map(i - end - i + start).toArray();}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static void fill2DIntArray(int[][] a, int val)Arrays.stream(a).forEach(x - Arrays.fill(x, val));>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static void sort(int[] a)Arrays.sort(a);}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] sort1(int [] a, boolean reverseOrder)Integer[] temp = Arrays.stream(a).mapToObj(x - x).toArray(Integer[]::new);> if(!reverseOrder) > {Arrays.sort(temp);}> else> {Arrays.sort(temp, Collections.reverseOrder());> }return Arrays.stream(temp).mapToInt(x - x).toArray();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] sort2(int [] a, boolean reverseOrder)if(!reverseOrder){> return Arrays.stream(a)> .mapToObj(x - x)> .sorted(Comparator.naturalOrder()).mapToInt(x - x).toArray();}> return Arrays.stream(a).mapToObj(x - x).sorted(Comparator.reverseOrder()).mapToInt(x - x).toArray();}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static void sort2DArrayByDimension(int[][] arr, int dim, boolean reverseOrder)> if(!reverseOrder)> {Arrays.sort(arr, Comparator.comparingInt((int[] a) - a[dim]));> }else{> Arrays.sort(arr, Comparator.comparingInt((int[] a) - a[dim]).reversed());}>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] extractDimension(int[][] a, int dim)Integer[] temp = Arrays.stream(a).map((int[] x) - x[dim]).toArray(Integer[]::new);> return Arrays.stream(temp).mapToInt(x - x).toArray();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int[] sumTwoArrays(int[] a1, int[] a2)int[] a = new int[a1.length];Arrays.setAll(a, i - a1[i] + a2[i]);return a;>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int productOfArray1(int[] a)return Arrays.stream(a).reduce(1, (x, y) - x * y);>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int productOfArray2(int[] a)return Arrays.stream(a).reduce((x, y) - x * y).getAsInt();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static Pairint[], int[] separateIntsIntoPosAndNeg(int[] a)> MapBoolean, ListInteger map = Arrays.stream(a) > .boxed().collect(Collectors.partitioningBy(x - x = 0));> ListInteger positive = map.get(true); > ListInteger negative = map.get(false);> int[] pos = positive.stream().mapToInt(x - x).toArray();int[] neg = negative.stream().mapToInt(x - x).toArray();> return Pair.of(pos, neg); >}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static char[] numberRangeToCharArray(int from, int to)> return IntStream.rangeClosed(from, to)> .mapToObj(x - Character.toString((char)(x- 1 + 'a')))> .collect(Collectors.joining()) > .toCharArray();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static MapInteger, ListInteger from2DIntArrayToMap(int[][] a)> MapInteger, ListInteger result => Arrays.stream(a).collect(> HashMap::new,> (map, item) - map.computeIfAbsent(item[0], x - new ArrayList()).add(item[1]),> HashMap::putAll);> return result;>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>staticT MapT, ListT from2DArrayToMap(T[][] a)> MapT, ListT result = Arrays.stream(a).collect(> HashMap::new,> (map, item) - map.computeIfAbsent(item[0], x -new ArrayList()).add(item[1]),> HashMap::putAll); > return result;>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static ListCharacter charArrayToListOfCharacter(char[] a)> String s = new String(a);> returns.chars().mapToObj(c - (char)c).collect(Collectors.toList());>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static Character[] stringToCharacterArray1(String s)return s.chars().mapToObj(c - (char)c).toArray(Character[]::new);>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static Character[] stringToCharacterArray2(String s)return IntStream.range(0, s.length()).mapToObj(s::charAt).toArray(Character[]::new);>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static String characterArrayToString(Character[] a)return Arrays.stream(a).map(Object::toString).collect(Collectors.joining());>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static char[] listOfCharacterToCharArray(ListCharacter list)> return list.stream().map(Object::toString).collect(Collectors.joining()).toCharArray();}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static String stringArrayToString(String[] a, String sep)> return Arrays.stream(a).collect(Collectors.joining(sep)); >}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static MapString,Long arrayOfWordsToMapOfWordCounts(String[] a)> return Arrays.stream(a).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static String longestStringInArray(String[] a)PairString,Integer longest = Arrays.stream(a)> .map(p - Pair.of(p, p.length())) > .max(Comparator.comparing(Pair::getRight)).get();> return longest.getLeft();>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()boolean check = Arrays.asList(1, 2, 3).equals(fromIntArrayToList(new int[] {1, 2, 3}));> if(!check) > {return false;}> Integer[] A = fromIntToIntegerArray1(new int[] {1, 2, 3});check = A[0] == 1 && A[1] == 2 && A[2] == 3;if(!check){> return false;> }A = fromIntToIntegerArray2(new int[] {1, 2, 3});> check = A[0] == 1 && A[1] == 2 && A[2] == 3; > if(!check)> {> return false;> }A = new Integer[] {1, 2, 3};check = Arrays.equals(new int[] {1, 2, 3}, fromIntegerToIntArray(A));> if(!check){return false;> }> check = Arrays.equals(new int[] {1, 2, 3}, fromListToIntArray(Arrays.asList(1, 2, 3)));if(!check)> {> return false;> }int[][] aa = new int[][] {{1,2}, {3,4}};check = Arrays.equals(new int[] {1, 2, 3, 4}, flatten2DArray(aa));> if(!check){return false;> }> check = Arrays.equals(new String[] {"1", "2", "3"}, fromIntToStringArray(new int[] {1, 2, 3}));> if(!check){return false;> }> check = Arrays.equals(new int[] {1, 2, 3}, fromStringToIntArray(new String[] {"1", "2", "3"}));> if(!check){return false;> }> check = Arrays.equals(new int[] {2, 3, 4, 5, 6}, arrayOfConsecutiveInts(2, 6));> if(!check)> {> return false;> }check = Arrays.equals(new int[] {6, 5, 4, 3, 2}, arrayOfConsecutiveIntsReversed(2, 6));> if(!check) > {return false;}> aa = new int[2][2];> fill2DIntArray(aa, 2);> check = Arrays.equals(new int[] {2, 2}, aa[0]) && Arrays.equals(new int[] {2, 2}, aa[1]);if(!check)> {> return false;> }int[] a = new int []{3, 1, 7, 4, 9, 2, 6, 5, 8};check = Arrays.equals(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, sort1(a, false));> if(!check) > {return false;}> check = Arrays.equals(new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1}, sort1(a, true));if(!check){> return false;> }check = Arrays.equals(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, sort2(a, false));> if(!check){return false;> }> check = Arrays.equals(new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1}, sort2(a, true));> if(!check)> {> return false;> }aa = new int[][] {{2, 0, 1}, {5, 4, 6}, {4, 3, 2}, {1, 2, 3}};> sort2DArrayByDimension(aa, 0, false); > check = Arrays.equals(new int[] {1, 2, 3}, aa[0]) && Arrays.equals(new int[] {2, 0, 1}, aa[1]) &&Arrays.equals(new int[] {4, 3, 2}, aa[2]) && Arrays.equals(new int[] {5, 4, 6}, aa[3]);> if(!check)> {> return false;> }aa = new int[][] {{2, 0, 1}, {5, 4, 6}, {4, 3, 2}, {1, 2, 3}};> sort2DArrayByDimension(aa, 1, false); > check = Arrays.equals(new int[] {2, 0, 1}, aa[0]) && Arrays.equals(new int[] {1, 2, 3}, aa[1]) &&Arrays.equals(new int[] {4, 3, 2}, aa[2]) && Arrays.equals(new int[] {5, 4, 6}, aa[3]);> if(!check)> {> return false;> }aa = new int[][] {{2, 0, 1}, {5, 4, 6}, {4, 3, 2}, {1, 2, 3}};> sort2DArrayByDimension(aa, 0, true); > check = Arrays.equals(new int[] {5, 4, 6}, aa[0]) && Arrays.equals(new int[] {4, 3, 2}, aa[1]) &&Arrays.equals(new int[] {2, 0, 1}, aa[2]) && Arrays.equals(new int[] {1, 2, 3}, aa[3]);> if(!check)> {> return false;> }check = Arrays.equals(new int[] {0, 4, 3, 2},> extractDimension(new int[][] {{2, 0, 1}, {5, 4, 6}, {4, 3, 2}, {1, 2, 3}}, 1));if(!check)> {> return false;> }check = Arrays.equals(new int[] {5, 7, 9}, sumTwoArrays(new int [] {1, 2, 3}, new int[] {4, 5, 6}));> if(!check) > {> return false;> }a = new int[] {3, 0, -5, 2, -4, 7, -1};Pairint[], int[] pair = separateIntsIntoPosAndNeg(a);> check = Arrays.equals(new int[] {3, 0, 2, 7}, pair.getLeft()) && > Arrays.equals(new int[] {-5, -4, -1}, pair.getRight());if(!check)> {> return false;> }check = Arrays.equals(new char[] {'c', 'd', 'e', 'f', 'g'}, numberRangeToCharArray(3, 7));pre data-role="codeBlock" data-info="js" class="language-javascript"> if(!check)> {return false;}> MapInteger, ListInteger result1 = from2DIntArrayToMap(new int[][] {{1, 2}, {2, 3}, {1, 4}});> check = Arrays.equals(new int[] {2, 4}, result1.get(1).stream().mapToInt(x - x).toArray()) &&Arrays.equals(new int[] {3}, result1.get(2).stream().mapToInt(x - x).toArray());pre data-role="codeBlock" data-info="js" class="language-javascript"> if(!check)> {return false;}> MapString, ListString result2 = from2DArrayToMap(new String[][] {{"nick", "90"}, {"paul", "70"}, {"nick", "100"}});check = result2.get("nick").size() == 2 && result2.get("nick").contains("90") && result2.get("nick").contains("100");> if(!check){return false;> }> check = Arrays.asList('A', 'B', 'C').equals(charArrayToListOfCharacter(new char[] {'A', 'B', 'C'}));if(!check)> {> return false;> }check = 24 == productOfArray1(new int[] {1, 2, 3, 4});> if(!check){return false;> }> check = Arrays.equals(new Character[] {'A', 'B', 'C'}, stringToCharacterArray1("ABC"));if(!check){> return false;> }> check = Arrays.equals(new Character[] {'A', 'B', 'C'}, stringToCharacterArray2("ABC"));if(!check){> return false;> }> check = characterArrayToString(new Character[] {'A', 'B', 'C'}).equals("ABC");if(!check)> {> return false;> }check = Arrays.equals(new char[] {'A', 'B', 'C'}, listOfCharacterToCharArray(Arrays.asList('A', 'B', 'C')));> if(!check)> {> return false;> }check = stringArrayToString(new String[] {"one", "two", "three"}, " ").equals("one two three");if(!check)> {> return false;> }MapString,Long countMap = arrayOfWordsToMapOfWordCounts(new String[] {"three", "one", "two", "three", "two", "three"});pre data-role="codeBlock" data-info="js" class="language-javascript"> check = countMap.get("one") == 1 && countMap.get("two") == 2 && countMap.get("three") == 3;> if(!check){return false;> }> check = longestStringInArray(new String[] {"a", "bb", "ccc", "dddd"}).equals("dddd");> if(!check){return false;> }> return true;}Notes:
1.
Make sure to userArrays.sort
for sorting in place. Using streamssorted
will not modify underlying collection.
Fibonacci
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int fibonacciWithStreamIterate(int n)return Stream.iterate(new int[] {0, 1}, t - new int[] {t[1], t[0] + t[1]})> .limit(n) > .map(t - t[1])> .skip(n - 1)> .findFirst().get();>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int fibonacciWithStreamGenerate(int n)IntSupplier intSupplier = new IntSupplier(){> int a = 0;> int b = 1;> @Override> public int getAsInt()> {> int c = a + b;> a = b;> b = c; > return b;> }};return IntStream.generate(intSupplier).limit(n - 1)> .skip(n - 2)> .findFirst()> .getAsInt();>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()boolean check = fibonacciWithStreamIterate(14) == 377;> if(!check){return false;> }> check = fibonacciWithStreamGenerate(14) == 377;> if(!check)> {return false;}> return true;>}
ForkJoinSumCalculator
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>public class ForkJoinSumCalculator extends RecursiveTaskLong> public static final long THRESHOLD = 10_000;> > private final long[] numbers;> private final int start;> private final int end;>public ForkJoinSumCalculator(long[] numbers){this(numbers, 0, numbers.length);}> > private ForkJoinSumCalculator(long[] numbers, int start, int end)> {> this.numbers = numbers; > this.start = start;> this.end = end;> }> {@Override> protected Long compute()int length = end - start;if (length = THRESHOLD){> return computeSequentially();> }> ForkJoinSumCalculator leftTask => new ForkJoinSumCalculator(numbers, start, start + length / 2);> leftTask.fork(); > ForkJoinSumCalculator rightTask => new ForkJoinSumCalculator(numbers, start + length / 2, end);Long rightResult = rightTask.compute();Long leftResult = leftTask.join();return leftResult + rightResult;}> > private long computeSequentially() > {long sum = 0;for (int i = start; i end; i++){> sum += numbers[i];> }> return sum;> }> long[] numbers = LongStream.rangeClosed(1, n).toArray();> ForkJoinTaskLong task = new ForkJoinSumCalculator(numbers);public static long forkJoinSum(long n)> {return new ForkJoinPool().invoke(task);}}
Optionals
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>public class Optionals/*> Consider a person who might have a car which might be insured> Some person may not have a car> Some person may have a car which is not insuredIn a typical application this would require a lot of null checks*/> > static class Insurance> {String insuranceName;Insurance(String name){> this.insuranceName = name;> }>String getInsuranceName(){> return insuranceName;> }> }> OptionalInsurance insuranceOptional;pre data-role="codeBlock" data-info="js" class="language-javascript"> Car(OptionalInsurance insuranceOptional)> { > this.insuranceOptional = insuranceOptional;> }>static class Car> {OptionalInsurance getInsuranceOptional()> {> return insuranceOptional; > }}> static class Person> {OptionalCar carOptional;Person(OptionalCar carOptional)> {> this.carOptional = carOptional; > }> }OptionalCar getCarOptional(){> return carOptional;}> > static String getInsuranceNameNoNullChecks(OptionalPerson personOptional){> return personOptional.flatMap(Person::getCarOptional)> .flatMap(Car::getInsuranceOptional)> .map(Insurance::getInsuranceName).orElse("Unknown");}>static String getInsuranceNameSameAsNullChecks(OptionalPerson personOptional)> {> if(personOptional.isPresent())> { > Person person = personOptional.get();> OptionalCar carOptional = person.getCarOptional();if(carOptional.isPresent())> {> Car car = carOptional.get(); > OptionalInsurance insuranceOptional = car.getInsuranceOptional();if(insuranceOptional.isPresent())> {> Insurance insurance = insuranceOptional.get();> return insurance.getInsuranceName();}}> }> return "Unknown";> }} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()Insurance insurance1 = new Insurance("Geico");> Car car1 = new Car(Optional.of(insurance1)); pre data-role="codeBlock" data-info="js" class="language-javascript"> Person person1 = new Person(Optional.of(car1));> String insuranceName = getInsuranceNameNoNullChecks(Optional.of(person1));> boolean check = insuranceName.equals("Geico"); > if(!check)> {return false;}> insuranceName = getInsuranceNameSameAsNullChecks(Optional.of(person1));> check = insuranceName.equals("Geico"); > if(!check)> {return false;}> Car car2 = new Car(Optional.empty());> Person person2 = new Person(Optional.of(car2));insuranceName = getInsuranceNameNoNullChecks(Optional.of(person2));> check = insuranceName.equals("Unknown"); > if(!check)> {return false;}> return true;>}
PairNumbers
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static Listint[] pairNumbers(int[] a1, int[] a2)> return Arrays.stream(a1).boxed().flatMap(i -pre data-role="codeBlock" data-info="js" class="language-javascript"> Arrays.stream(a2).mapToObj(j - new int[] {i, j})) > .collect(Collectors.toList());>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()int [] a1 = {1, 2, 3};int [] a2 = {3, 4};> Listint[] result = pairNumbers(a1, a2);boolean check = result.size() == 6;if(!check)> {> return false;> }check = Arrays.equals(new int[] {1, 3}, result.get(0)) &&> Arrays.equals(new int[] {1, 4}, result.get(1)) &&> Arrays.equals(new int[] {2, 3}, result.get(2)) && > Arrays.equals(new int[] {2, 4}, result.get(3)) &&> Arrays.equals(new int[] {3, 3}, result.get(4)) && > Arrays.equals(new int[] {3, 4}, result.get(5));pre data-role="codeBlock" data-info="js" class="language-javascript"> if(!check)> {return false;}> return true;>}
Primes
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static private boolean isPrime(int n)int candidateRoot = (int)Math.sqrt(n);return IntStream.rangeClosed(2, candidateRoot).noneMatch(i - n % i == 0);>}> >static int[] genPrimesUpTo(int n)MapBoolean,ListInteger map = IntStream.rangeClosed(2, n).boxed().collect(pre data-role="codeBlock" data-info="js" class="language-javascript"> Collectors.partitioningBy(x - isPrime(x)));> return map.get(true).stream().mapToInt(x - x).toArray();} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()boolean check = Arrays.equals(new int[] {2, 3, 5, 7}, genPrimesUpTo(7));> if(!check){return false;> }> return true;}
PrimeCollector
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>public class PrimeCollector implements CollectorInteger, MapBoolean, ListInteger, MapBoolean,ListIntegerprivate static ListInteger takeWhile(ListInteger list, PredicateInteger p)> { > int i = 0;> for(Integer item : list)> {> if(!p.test(item))> { > return list.subList(0, i);> }> i++;> }return list;}> > private static boolean isPrime(ListInteger primes, int candidate)> {> int candidateSqrt = (int) Math.sqrt(candidate);> return takeWhile(primes, i - i = candidateSqrt).stream().noneMatch(j - candidate % j == 0);> }@Override> public SupplierMapBoolean, ListInteger supplier(){> return () - new HashMapBoolean, ListInteger() {{put(true, new ArrayList());put(false, new ArrayList());}};> }>@Overridepublic BiConsumerMapBoolean, ListInteger,Integer accumulator()> {> return (MapBoolean,ListInteger acc, Integer candidate) - {acc.get(isPrime(acc.get(true), candidate)).add(candidate);};}>@Overridepublic BinaryOperatorMapBoolean, ListInteger combiner()pre data-role="codeBlock" data-info="js" class="language-javascript"> {return (MapBoolean,ListInteger m1, MapBoolean, ListInteger m2) - {> m1.get(true).addAll(m2.get(true));> m1.get(false).addAll(m2.get(false));return m1;> };> }>@Overridepublic FunctionMapBoolean, ListInteger, MapBoolean, ListInteger finisher()> {> return Function.identity(); > }> {> return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH, CONCURRENT));@Override> public SetCharacteristics characteristics()}>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()MapBoolean, ListInteger map = IntStream.rangeClosed(2, 20).boxed().collect(new PrimeCollector());int[] primes = map.get(true).stream().mapToInt(x - x).toArray();> boolean check = Arrays.equals(new int[] {2, 3, 5, 7, 11, 13, 17, 19}, primes);> if(!check)> {> return false;> }return true;}
PythagoreanTuples
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static Listint[] generate(int n)Listdouble[] triples =IntStream.rangeClosed(1, n).boxed().flatMap(a - IntStream.rangeClosed(a, n).mapToObj(b - new double[] {a, b, Math.sqrt(a * a + b * b)}))> .filter(t - t[2] % 1 == 0).collect(Collectors.toList());> return triples.stream().map(x - new int[] {(int)x[0], (int)x[1], (int)x[2]}).collect(Collectors.toList());>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()Listint[] triples = generate(20);boolean check = Arrays.equals(new int[] {3, 4, 5}, triples.get(0)) &&> Arrays.equals(new int[] {5, 12, 13}, triples.get(1)) &&Arrays.equals(new int[] {6, 8, 10}, triples.get(2)) &&> Arrays.equals(new int[] {8, 15, 17}, triples.get(3)) &&> Arrays.equals(new int[] {9, 12, 15}, triples.get(4)) && > Arrays.equals(new int[] {12, 16, 20}, triples.get(5)) &&Arrays.equals(new int[] {15, 20, 25}, triples.get(6));if(!check){> return false;> }return true;}
WordCounter
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>public class WordCounterprivate int counter;private boolean lastSpace;> public WordCounter(int counter, boolean lastSpace)> { > this.counter = counter; > this.lastSpace = lastSpace;> }> {> return lastSpace ? this : new WordCounter(counter, true);> }> else> { > return lastSpace ? new WordCounter(counter + 1, false) : this;> }> }public WordCounter accumulate(Character c){> if(Character.isWhitespace(c))> }public WordCounter combine(WordCounter wordCounter){> return new WordCounter(counter + wordCounter.counter, wordCounter.lastSpace);> return counter;> }public int getCounter()> {} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()String sentence = "one two three four five six";> StreamCharacter stream = sentence.chars().mapToObj(e - (char)e);> WordCounter wordCounter = stream.reduce(new WordCounter(0, true), > WordCounter::accumulate, WordCounter::combine);> boolean check = wordCounter.getCounter() == 6;> if(!check) > {> return false;> }return true;}
WordCounterSplitterator
Tests