Java LinqCollection 仿Linq的list常用函数

目前支持find,findAll,sort,select,remove等,java不支持lamda函数,因此用接口代替

public interface Fun<T1,T2> {
	public T2 process(T1 item);
}

public interface Predicate<T> {
	/**
	 * 是否满足
	 * @param item
	 * @return
	 */
	public boolean evaluate(T item);
}

接下来是具体的实现:

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);
	}
	
	/**
	 * 查找首条符合条件的记录
	 * @param predicate 条件
	 * @return
	 */
	public T find(Predicate<T> predicate){
		for(T item: this){
			if(predicate.evaluate(item)){
				return item;
			}
		}
		return null;
	}
	
	/**
	 * 按条件删除
	 * @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 ComparableItem<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;
		}
		
		@Override
		public int compareTo(Object o) {
			return ((Comparable)(this.keySelect.process(this.data))).compareTo((Comparable)(this.keySelect.process(((ComparableItem<T>)o).data)));
		}
		
	}
	
	/**
	 * 选择
	 * @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;
	}
	
	/**
	 * 按指定字段排序
	 * @param keySelect(选择排序的字段)
	 */
	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);
        }
	}
	
	/**
	 * 查找所有符合条件的记录
	 * @param predicate
	 * @return
	 */
	public LinqCollection<T> findAll(Predicate<T> predicate){
		LinqCollection<T> result = new LinqCollection<T>();
		for(T item: this){
			if(predicate.evaluate(item)){
				result.add(item);
			}
		}
		return result;
	}
	
	/**
	 * 是否存在
	 * @param predicate
	 * @return
	 */
	public boolean exist(Predicate<T> predicate){
		return this.find(predicate)!=null;
	}
}

  使用举例:

cleanItems.sort(new Fun<SameNameSinger, Integer>() {
				@Override
				public Integer process(SameNameSinger item) {
					return item.getNameIndex();
				}			
			});

  

 

 

posted @ 2015-08-27 19:25  JadePeng  阅读(3403)  评论(0编辑  收藏  举报