// another version of comparable lists, using Comparator interface import java.util.function.*; /* Another built-in interface of Java: interface Predicate // from java.util.function { boolean test(T x); } */ // now for some of my own interfaces ... interface fun // function with intype and outtype { OutT f(InT x); } // this is similar to java.util.function.Function interface, and the // following "interface adapter" will allow interoperability: class funfun implements Function { protected final fun myfun; public funfun(fun ff) {myfun=ff;} public R apply(T x) { return myfun.f(x); } } // another interface: interface bop // binary operator like *, +, etc { T op(T x, T y); } public class CList2 extends LinkedList { public CList2() { super(); // calls superclass constructor } public CList2(LinkedList M) // create weak copy { if (M!=null) { last = M.last; first=M.first; size=M.size; } }// alt constructor with type casting. // count howmany values of list satisfy public int howmany(Predicate p) { int cx = 0; //counter for(node i=first;i!=null&&i!=last.next;i=i.next) if (p.test(i.item)) cx++; return cx; } public boolean exists(Predicate p) { for(node i=first;i!=null&&i!=last.next;i=i.next) if (p.test(i.item)) return true; return false; } public boolean forall(Predicate p) { return !exists( (x)->!p.test(x) ); } public void mapfun(fun imfun) // destructively change list with imfun { for(node i=first;i!=null&&i!=last.next;i=i.next) i.item = imfun.f(i.item); } public CList2 map(fun yourenofun) { CList2 L =new CList2(); for(T x:this) L.add( yourenofun.f(x) ); return L; } public T reduce(bop B, T id) // apply binary operator with identity id { T ax = id; // accumulator set to identity (default) for(node i=first;i!=null&&i!=last.next;i=i.next) ax = B.op(ax,i.item); return ax; } // for mapping to different type of output: declares new type var Ot: public CList2 mapf(fun doublethefun) { CList2 L =new CList2(); for(T x:this) L.add( doublethefun.f(x) ); return L; } // a more complicated prediate: // testing for primality: public static boolean prime(int n) { if (n==2) return true; if (n<2 || n%2==0) return false; int limit = (int)(Math.sqrt(n))+1; for(int i=3;i<=limit;i+=2) if (n%i==0) return false; return true; } public static void main(String[] av) { CList2 M= new CList2(); for(int i=0;i<20;i++) M.add((int)(Math.random()*100)); System.out.println(M); CList2 N = M.map( (x)->x*x ); System.out.println(N); Integer sum = N.reduce( ((x,y)->x+y), 0); System.out.println("sum of N: "+sum); CList2 B = N.mapf((x)->x%2==1); System.out.println(B); System.out.println("all odd: "+B.reduce((x,y)->x&&y, true)); System.out.println("all even: "+N.forall( (x)->x%2==0)); // how many primes in the list M? CList2 P = M.mapf( (x)->{if (prime(x)) return x+" is prime\n"; else return "";} ); System.out.println( P.reduce((x,y)->x+y, "") ); }//main }//CList2