Skip to content

Instantly share code, notes, and snippets.

@bkrmendy
Created September 28, 2021 20:33
Show Gist options
  • Save bkrmendy/721b1fc9d6d61615849d6b78e4167a79 to your computer and use it in GitHub Desktop.
Save bkrmendy/721b1fc9d6d61615849d6b78e4167a79 to your computer and use it in GitHub Desktop.
package com.berci;
import java.util.ArrayList;
import java.util.Arrays;
record Tuple<T, U>(T one, U other){}
@FunctionalInterface
interface Combine<T> {
T method(T left, T right);
}
@FunctionalInterface
interface ProcessElement<T> {
T method(T t);
}
@FunctionalInterface
interface Filter<T> {
boolean method(T t);
}
class CombineImpl<T> {
T combine(ArrayList<T> elems, T start, Combine<T> combineFn) {
for (T elem : elems) {
start = combineFn.method(start, elem);
}
return start;
}
ArrayList<T> process(ArrayList<T> elems, ProcessElement<T> processFn) {
ArrayList<T> result = new ArrayList<>();
for (T elem : elems) {
T processedElem = processFn.method(elem);
result.add(processedElem);
}
return result;
}
Tuple<ArrayList<T>, ArrayList<T>> partition(ArrayList<T> elems, Filter<T> filterFn) {
Tuple<ArrayList<T>, ArrayList<T>> result = new Tuple<>(new ArrayList<>(), new ArrayList<>());
for (T elem : elems) {
if (filterFn.method(elem)) {
result.one().add(elem);
} else {
result.other().add(elem);
}
}
return result;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
ArrayList<String> strings = new ArrayList<>(Arrays.asList("a", "aa", "aaa", "aaaa", "aaaaa"));
CombineImpl<Integer> intCombiner = new CombineImpl<>();
Integer sum = new CombineImpl<Integer>().combine(numbers, 0, (a, b) -> a + b);
Integer product = new CombineImpl<Integer>().combine(numbers, 1, (a, b) -> a * b);
ArrayList<Integer> plusOnes = new CombineImpl<Integer>().process(numbers, (a) -> a + 1);
ArrayList<String> exclamations = new CombineImpl<String>().process(strings, s -> s.concat("!"));
Tuple<ArrayList<String>, ArrayList<String>> result = new CombineImpl<String>().partition(strings, e -> e.length() % 2 == 0);
System.out.println("evens:");
System.out.println(result.one());
System.out.println("odds:");
System.out.println(result.other());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment