Skip to content

Instantly share code, notes, and snippets.

@lingpri
Created June 6, 2023 21:52
Show Gist options
  • Save lingpri/12f65c31507a4b5460d221abae777036 to your computer and use it in GitHub Desktop.
Save lingpri/12f65c31507a4b5460d221abae777036 to your computer and use it in GitHub Desktop.
Learning Generics
import java.math.*;
import java.util.concurrent.atomic.*;
import java.util.*;
interface Combiner<T> {T combine(T x, T y); }
interface UnaryFunction<R,T> {R function(T x);}
interface Collector<T> extends UnaryFunction<T,T> {
T result(); //extract result of collecting parameter
}
interface UnaryPredicate<T> {boolean test(T x);}
public class Functional {
static class GreaterThan<T extends Comparable<T>> implements UnaryPredicate<T> {
private T bound;
public GreaterThan(T bound) {this.bound = bound;}
@Override
public boolean test(T x) {
return x.compareTo(bound) > 0;
}
}
public static <T> List<T> filter(Iterable<T> seq, UnaryPredicate<T> pred) {
List<T> result = new ArrayList<T>();
for(T t:seq)
if(pred.test(t))
result.add(t);
return result;
}
public static void main(String[] args) {
List<Integer> li = Arrays.asList(1,2,3,4,5,6,7);
List<Integer> filteredResult = filter(li, new GreaterThan<Integer>(4));
for (Integer result : filteredResult) {
System.out.println(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment