• Java中 filter()函数的用法


    Java中 filter()函数的用法

    介绍

    Java 8 Stream接口引入了filter()方法,可用于根据特定条件从对象集合中过滤出某些元素。这个条件应该指定为filter()方法接受作为参数的谓词。

    predicate接口定义了一个名为test()的抽象方法,该方法接受泛型类型T的对象并返回一个布尔值。

    让我们编写一些代码,以便更清楚地理解filter方法。看看下面的Dish类。

    详细代码

    package com.liu.filter;
    /**
     * @Decision TODO
     * @author liusx
     * @Date 2021年8月17日
     */
    public class Dish {
    	private String name;
        private Boolean vegitarian;
        private Integer calaries;
        private Type type;
        public Dish(String name, Boolean vegitarian, Integer calaries, Type type) {
             super();
             this.name = name;
             this.vegitarian = vegitarian;
             this.calaries = calaries;
             this.type = type;
        }
        public Boolean getVegitarian() {
            return vegitarian;
        }
        public void setVegitarian(Boolean vegitarian) {
            this.vegitarian = vegitarian;
        }
        public Type getType() {
            return type;
        }
        public void setType(Type type) {
            this.type = type;
        }
        public enum Type { MEAT, FISH, OTHER };
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    让我们想想,我们想要从所有菜的列表中只过滤素食菜。下面是Java 8之前的方法。

    Java8之前的写法

    public static List<Dish> getVegetarianDishes_old(List<Dish> menus) {
    		List<Dish> vegetarianDishes = new ArrayList<Dish>();//找是蔬菜的菜单
    		for (Dish d : menus) {
    			if (d.getVegitarian()) {
    				vegetarianDishes.add(d);
    			}
    		}
    		return vegetarianDishes;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    上述方法称为外部迭代,我们显式地管理数据集合上的迭代。

    如何使用Java 8实现这一点?它只是一个单行问题,如下所示。

    Java8写法1

    public static List<Dish> getVegetarianDishes_new(List<Dish> menus) {
    		List<Dish> vegitarianDishes = menus.stream()//找是蔬菜的菜单
                    .filter(d -> d.getVegitarian())
                    .collect(Collectors.toList());
    		return vegitarianDishes;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    我们以Lambda表达式的形式将Predicate实例传递给filter()方法。

    同样,我们可以使用java 8方法引用将Predicate实例传递给filter()方法,如下所示。

    Java8写法2

    List<Dish> menu = ....
    List<Dish> vegitarianDishes = menu.stream()
                                        .filter(Dish::getVegitarian)
                                        .collect(Collectors.toList());
    
    • 1
    • 2
    • 3
    • 4

    Dish::getVegitarian是Java 8方法引用的语法。它指的是Dish类的getVegitarian()方法。

    filter()方法返回一个盘子流,collect()方法将这个流转换成一个列表。“收集”操作称为终端操作。

    现在假设,我们想要的前三道菜的热量超过300卡路里。流支持limit(n)方法,它返回不超过给定大小的另一个流。请求的大小作为参数传递给limit。

    List<Dish> menu = ....
    List<Dish> threeHighCalaricDish = menu.stream()
                                             .filter(d -> d.getCalaries() > 300)
                                             .limit(3)
                                             .collect(Collectors.toList());
    
    • 1
    • 2
    • 3
    • 4
    • 5

    类似地,如果我们想跳过前3个元素,流支持skip(n)方法来返回丢弃前n个元素的流。如果流的元素少于n,则返回一个空流。注意limit(n)和skip(n)是互补的!

    如果使用流来过滤前两道肉类菜肴,如下:

    List<Dish> menu = ....
    List<Dish> meatDishes = menu.stream()
                                      .filter(d -> d.getType() == Dish.Type.MEAT)
                                      .limit(2)
                                      .collect(Collectors.toList())
    
    • 1
    • 2
    • 3
    • 4
    • 5

    造数以及测试类代码

    package com.liu.filter;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    import com.alibaba.fastjson.JSON;
    import com.liu.filter.Dish.Type;
    /**
     * @Decision 测试在Java 8中使用filter()方法 与8之前的方法区别
     * @author liusx
     * @Date 2021年8月17日
     */
    public class TestFilter {
    	public static void main(String[] args) {
    		List<Dish> menus = getAllMenus();
    		//java8之前的方法
    		List<Dish> vegetarianDishes = getVegetarianDishes_old(menus);
    	    System.out.println("old方法::"+JSON.toJSONString(vegetarianDishes));
    	   //java8之后的方法
    	    List<Dish> vegetarianDishes2 = getVegetarianDishes_new(menus);
    	    System.out.println("new方法::"+JSON.toJSONString(vegetarianDishes2));
    	}
    	/**
    	 * @decision java8之前方法
    	 * @param menus
    	 * @return
    	 * @author liusx
    	 * @Date 2021年8月17日
    	 */
    	public static List<Dish> getVegetarianDishes_old(List<Dish> menus) {
    		List<Dish> vegetarianDishes = new ArrayList<Dish>();//找是蔬菜的菜单
    		for (Dish d : menus) {
    			if (d.getVegitarian()) {
    				vegetarianDishes.add(d);
    			}
    		}
    		return vegetarianDishes;
    	}
    	/**
    	 * @decision java8方法
    	 * @param menus
    	 * @return
    	 * @author liusx
    	 * @Date 2021年8月17日
    	 */
    	public static List<Dish> getVegetarianDishes_new(List<Dish> menus) {
    		List<Dish> vegitarianDishes = menus.stream()//找是蔬菜的菜单
                    .filter(d -> d.getVegitarian())
                    .collect(Collectors.toList());
    		return vegitarianDishes;
    	}
    	/**
    	 * @decision 造menu数据
    	 * @return
    	 * @author liusx
    	 * @Date 2021年8月17日
    	 */
    	public static List<Dish> getAllMenus() {
    		List<Dish> menus = new ArrayList<Dish>();//所有的菜
    		Dish d1 = new Dish("油麦菜", true, 100, Type.OTHER);
    		Dish d2 = new Dish("青鱼", false, 100, Type.FISH);
    		Dish d3 = new Dish("大鹅", false, 100, Type.MEAT);
    		Dish d4 = new Dish("菠菜", true, 100, Type.OTHER);
    		menus.add(d1);
    		menus.add(d2);
    		menus.add(d3);
    		menus.add(d4);
    		return menus;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77

    测试结果

    在这里插入图片描述

    参考资料链接:

    https://www.javacodegeeks.com/2018/07/filter-method-java-8.html.

    https://blog.csdn.net/suixinfeixiangfei/article/details/119767458
  • 相关阅读:
    两线段是否相交模板
    树的距离
    Codeforces Round #369 (Div. 2)-D Directed Roads
    Codeforces Round #369 (Div. 2)-C Coloring Trees
    Codeforces Round #374 (Div. 2)-D Maxim and Array
    zstu-4243 牛吃草
    Codeforces Round #447 (Div. 2)
    zstu 4247-萌新的旅行
    CDQ分治求前缀和
    self.faceshowing = !self.facshowing无效,了,原来set
  • 原文地址:https://www.cnblogs.com/sunny3158/p/16694417.html
Copyright © 2020-2023  润新知