直接上代码
Blog.Java
public class Blog { public Blog(int id,String name) { Id=id; Name=name; } public int Id; public String Name; }
util.java
import java.util.ArrayList;import java.util.List;public final class util{ public static void Each(List list, Action action) { for (T item : list) { action.invoke(item); } } public static T Last(List list, Func func) { for (int i = list.size() - 1; i > -1; i--) { if (func.invoke(list.get(i))) { return list.get(i); } } return null; } public static T First(List list, Func func) { for (T item : list) { if (func.invoke(item)) { return item; } } return null; } public static List Where(List list, Func func) { List tempList = new ArrayList (); for (T item : list) { if (func.invoke(item)) { tempList.add(item); } } return tempList; } public interface Func { public boolean invoke(T o); } public interface Action { public void invoke(T o); }}
测试代码
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class progrmas { public static void main(String[] args) { Listlist = new ArrayList (); list.add(new Blog(1, "blog 1")); list.add(new Blog(2, "blog 2")); list.add(new Blog(3, "blog 2")); list.add(new Blog(4, "blog 4")); List result = new ArrayList (); final int id = 1; // 查询 List result2 = util.Where(list, new util.Func () { @Override public boolean invoke(Blog blog) { return blog.Name.contains("2"); } }); //Java 8支持Lambda时,使用会相当简洁 // List result2 = util.Where(list,(b)->b.Name.contains("2")); // 打印结果 util.Each(result2, new util.Action () { @Override public void invoke(Blog o) { System.out.print(String.valueOf(o.Id) + "------" + o.Name); } }); //Java 8支持Lambda时,使用会相当简洁 // util.Each(result2,(b)->System.out.println(String.valueOf(b.Id) +"------" + b.Name)); }}