java8 filter return_java8实战:filter的简单使用

《JAVA8实战》中的例子

要实现的功能:通过Apple的color或weight属性,对List进行筛选。

1、首先定义com.owl.entity.Apple:

package com.owl.entity;

public classApple {privateString color;privateInteger weight;publicString getColor() {returncolor;

}public voidsetColor(String color) {this.color =color;

}publicInteger getWeight() {returnweight;

}public voidsetWeight(Integer weight) {this.weight =weight;

}

}

2、生成一个简单的List集合

packagecom.owl.app;importjava.util.ArrayList;importjava.util.List;importcom.owl.entity.Apple;public classdemo {public static voidmain(String[] args) {

List appleList = new ArrayList();

Apple redApple= newApple();

redApple.setColor("red");

redApple.setWeight(180);

appleList.add(redApple);

Apple greenApple= newApple();

greenApple.setColor("green");

greenApple.setWeight(120);

appleList.add(greenApple);

}

}

3、在com.owl.entity.Apple中定义筛选条件(绿苹果或者重量大于150的苹果)

public static booleanisGreenApple(Apple apple) {return "green".equals(apple.getColor());

}public static booleanisHeavyApple(Apple apple) {return apple.getWeight() > 150;

}

4、在com.owl.app.demo中定义接口:

public interface Predicate{booleantest(T t);

}

5、在com.owl.app.demo中定义filter方法:

static List AppleFilter(List apples, Predicatep) {

List resultApples = new ArrayList();for(Apple apple:apples) {if(p.test(apple)) {

resultApples.add(apple);

}

}returnresultApples;

}

6、在main函数中使用filter筛选苹果

List greenAppleSet =AppleFilter(appleList, Apple::isGreenApple);

List heavyAppleSet =AppleFilter(appleList, Apple::isHeavyApple);

System.out.println("=======绿苹果=======");for(Apple apple:greenAppleSet) {

System.out.println(apple.getColor());

}

System.out.println("=======大苹果=======");for(Apple apple:heavyAppleSet) {

System.out.println(apple.getWeight());

}

结果:

20190106121928287225.png

为了实现上述功能,除了需要定义筛选条件之外,仍需要定义Predicate和AppleFilter方法未免太过麻烦,通过lambda表达式有更简单的写法:

List greenAppleSet = appleList.stream().filter((Apple apple)->apple.getColor().equals("green")).collect(Collectors.toList());

List heavyAppleSet = appleList.stream().filter((Apple apple)->apple.getWeight()>150).collect(Collectors.toList());

System.out.println("=======绿苹果=======");

for (Apple apple:greenAppleSet) {

System.out.println(apple.getColor());

}

System.out.println("=======大苹果=======");

for (Apple apple:heavyAppleSet) {

System.out.println(apple.getWeight());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值