Java LinqCollection is used to simulate the list common functions of Linq, and linqcollectionlinq
Currently, find, findAll, sort, select, and remove are supported. java does not support lamda functions, so it is replaced by interfaces.
Public interface Fun <T1, T2> {public T2 process (T1 item );} public interface Predicate <T> {/*** whether * @ param item * @ return */public boolean evaluate (T item );}
The following is the specific implementation:
Public class LinqCollection <T> extends java. util. arrayList <T> {/*** serialVersionUID */private static final long serialVersionUID =-5042194313851746204L; public LinqCollection () {super ();} public LinqCollection (Collection <? Extends T> c) {super (c );} /*** find the first qualified record * @ param predicate condition * @ return */public T find (Predicate <T> predicate) {for (T item: this) {if (predicate. evaluate (item) {return item;} return null;}/*** Delete by condition * @ param predicate */public void remove (Predicate <T> predicate) {ListIterator <T> I = this. listIterator (); while (I. hasNext () {T c = I. next (); if (predicate. evaluate (c) {I. remove () ;}} class Comparabl EItem <T> implements Comparable {T data; Fun <T,?> KeySelect = null; public <T2 extends Comparable <? Super T2> ComparableItem (T item, Fun <T, T2> keySelect) {this. keySelect = keySelect; this. data = item ;}@ Overridepublic int compareTo (Object o) {return (Comparable) (this. keySelect. process (this. data ))). compareTo (Comparable) (this. keySelect. process (ComparableItem <T>) o ). data);}/*** select * @ param keySelect * @ return */public <T2> LinqCollection <T2> select (Fun <T, T2> keySelect) {LinqCollection <T2> result = New LinqCollection <T2> (); for (T item: this) {result. add (keySelect. process (item);} return result;}/*** sort by specified field * @ param keySelect (select the sorted field) */public <T2 extends Comparable <? Super T2> void sort (Fun <T, T2> keySelect) {List <ComparableItem <T> items = Lists. newArrayList (); for (T item: this) {items. add (new ComparableItem <T> (item, keySelect);} Collections. sort (items); ListIterator I = this. listIterator (); for (int j = 0; j <items. size (); j ++) {I. next (); I. set (items. get (j ). data) ;}}/*** find all matching records * @ param predicate * @ return */public LinqCollection <T> findAll (Predicate <T> p Redicate) {LinqCollection <T> result = new LinqCollection <T> (); for (T item: this) {if (predicate. evaluate (item) {result. add (item) ;}} return result ;}/ *** whether * @ param predicate * @ return */public boolean exist (Predicate <T> predicate) {return this. find (predicate )! = Null ;}}
Example:
cleanItems.sort(new Fun<SameNameSinger, Integer>() {@Overridepublic Integer process(SameNameSinger item) {return item.getNameIndex();}});