函数式接口详解(Java)-CSDN博客
下面是一个去重的代码
/**
 * 学习Function匿名函数 和Predicate匿名函数 的定义
 * @author Administrator
 *
 */
public class DistinctFilterList {
    public static final List<Dish> menu =
            Arrays.asList( new Dish("pork", false, 800, Type.MEAT),
                           new Dish("beef", false, 700, Type.MEAT),
                           new Dish("beef", false, 700, Type.MEAT),
                           new Dish("chicken", false, 400, Type.MEAT)
                           );
    
	public static void main(String[] args) {
	    	List<Dish> dishList = (List<Dish>) menu.stream()
	        		.filter(distinctByKey(getNameFunction))
	                .collect(toList());
	    	dishList.forEach(dish -> System.out.println("----"+ dish.getName()));
	}
	
     //获取名字的函数
	private static Function<Dish,String> getNameFunction = new Function<Dish, String>(){
		@Override
		public String apply(Dish t) {
			return t.getName();
		}
    };
	//依据获取名字的函数, 等到boolean返回结果
	private static <T> Predicate<T> distinctByKey(Function<? super T, ?> function) {
	    Set<Object> set = Sets.newConcurrentHashSet();
	    return new Predicate<T>() {
			@Override
			public boolean test(T obj) {
				return set.add(function.apply(obj));
			}
	    };
	}
} 
有个疑问:
distinctByKey是静态方法, 静态方法中的局部变量,会在静态方法被调用时初始化, distinctByKey中Set<String> set = Sets.newConcurrentHashSet(); 是个局部变量, 他怎么做到去重?

以上是文心一言的回答, 它强调使用函数作为参数, 只调用了一次静态方法 distinctByKey. 静态方法内部完成了去重. 整个过程打包运行.
理解还是不透彻, 看到的朋友, 愿闻高见.



















