Created
June 6, 2023 21:52
-
-
Save lingpri/12f65c31507a4b5460d221abae777036 to your computer and use it in GitHub Desktop.
Learning Generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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