list集合中的筛选案例
本文记录学习java8的一些总结。
以下主要介绍从list集合中进行筛选的一些案例,以供和java8提供的lambda方式做一些对比,仅供参考。
一、传统的筛选方法
//从苹果集合中筛选出green颜色的苹果
public static List<Apple> findGreenApple(List<Apple> list){
List<Apple> newList = new ArrayList<>();
for (Apple apple : list){
if ("green".equals(apple.getColor())){
newList.add(apple);
}
}
return newList;
}
衍生出来的另一种:
//从苹果集合中筛选出某个颜色的苹果
public static List<Apple> findGreenApple(List<Apple> list,String color){
List<Apple> newList = new ArrayList<>();
for (Apple apple : list){
if (color.equals(apple.getColor())){
newList.add(apple);
}
}
return newList;
}
二、函数式接口的多个条件进行筛选
创建一个接口:
public interface AppleFilter{
boolean checkApp(Apple apple);
}
实现接口进行自定义条件筛选:
//苹果颜色为green,重量大于150的返回true
public static class Green150WeightApple implements AppleFilter{
@Override
public boolean checkApp(Apple apple) {
return "green".equals(apple.getColor())&&apple.getWeight()>150;
}
}
接着把集合和自定义条件筛选的类带入到方法中:
//根据appleFilter接口实现自定义筛选
public static List<Apple> findApple(List<Apple> list,AppleFilter appleFilter){
List<Apple> newList = new ArrayList<>();
for (Apple apple : list){
if (appleFilter.checkApp(apple)){
newList.add(apple);
}
}
return newList;
}
三、通过匿名内部类实现自定义筛选
//通过实现接口AppleFilter并重写checkApp方法来筛选苹果
List<Apple> yellowApples = findApple(list, new AppleFilter() {
public boolean checkApp(Apple apple){
return "yellow".equals(apple.getColor())&&apple.getWeight()>100;
}
});
四、通过Lambda表达式实现的筛选
//筛选list集合中颜色是green的苹果
List<Apple> greenApples = findApple(list,(Apple apple) -> {
return apple.getColor().equals("green");
});
或者这样写:
//筛选list集合中颜色是green的苹果
List<Apple> greenApples = findApple(list,apple -> {
return apple.getColor().equals("green");
});
五、线程经典写法
//定义一个线程
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
//启动线程
thread.start();
或者这样写:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}).start();
//等待执行中断的信号
Thread.currentThread().join();
六、线程Lambda写法
new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}).start();
//另一种写法
new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
案例中Apple类为:
public class Apple {
private String color;
private long weight;
public Apple(String color, long weight) {
this.color = color;
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public long getWeight() {
return weight;
}
public void setWeight(long weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Apple{" +
"color='" + color + '\'' +
", weight=" + weight +
'}';
}
}