转载请注明出处:http://blog.youkuaiyun.com/u012250875/article/details/78205841
一般都是for循环对每一个元素进行if判断,天天写for循环确实难受,其实可以按js中的filter来写。
1.定义接口
/**
* 过滤器
* @author puyf
* @param <T>
*/
public interface Filter<T> {
/**
* 筛选是否通过
* @param t
* @return true 表示通过
*/
boolean pass(T t);
}
2.定义工具方法
/**
* @author puyf
* @Description:过滤集合
* @param datas 数据源
* @param condition 过滤条件
* @return 返回过滤后的集合
*/
public static <T> List<T> filter(Collection<T> datas, Filter<T> condition) {
List<T> result = new ArrayList<>();
if (condition != null) {
for (T t : datas) {
if (condition.pass(t)) {
result.add(t);
}
}
} else {
return new ArrayList<>(datas);
}
return result;
}
3.使用
最后配合java8的lambda表达式,这么来做集合元素过滤的时候还是比较方便
public static void main(String[] args) {
List<Integer> data = new ArrayList<>(Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 100, -1, -2 }));
System.out.println("过滤出大于3的数:" + filter(data, (x) -> {
return x > 3;
}));
System.out.println("过滤出大于3的偶数:" + filter(data, (x) -> {
return x > 3 && ((x & 1) == 0);
}));
}
//执行结果:
过滤出大于3的数:[4, 5, 6, 7, 100]
过滤出大于3的偶数:[4, 6, 100]
更多集合操作(点击查看)