龙空技术网

java8之行为参数化,你用了吗?

IT小熊实验室丶 74

前言:

今天我们对“java参数化”都比较关怀,我们都需要了解一些“java参数化”的相关资讯。那么小编在网上搜集了一些对于“java参数化””的相关知识,希望你们能喜欢,大家一起来了解一下吧!

java8之行为参数化,你用了吗?

java8新增加了方法引用::语法(将方法作为参数)。将方法的引用传递进去,可以极大地简化你的代码。

需求1,将库存中的苹果按照重量排序:

在java8之前应该是这么写:

Collections.sort(inventory, new Comparator<Apple>(){ public int compare(Apple a1, Apple a2) { return a1.getWeight().compareTo(a2.getWeight()); }})

在java8中,可以这么实现:

inventory.sort(comparing(Apple::getWeight);

需求2,找到当前文件夹下所有的隐藏文件:

在java8之前应该是这么写:

File[] hiddenFiles = new File(".").listFiles(new FileFilter(){ public boolean accept(File file) { return file.isHidden(); }})

需要将方法用对象包装,然后将对象传递进去。

在java8中,可以这么实现:

File[] hiddenFiles = new File(".").listFiles(File::isHidden);

直接传递方法引用。

选苹果

选出仓库中所有的绿苹果

在java8之前应该是这么写:

public static List<Apple> filterGreenApple(List<Apple> inventory){ List<Apple> result = new ArrayList<>(); for (Apple apple : inventory){ if ("green".equals(apple.getColor())) { result.add(apple); } }}

选出重量大于150克的苹果

在java8之前应该是这么写:

public static List<Apple> filterHeavyApples(List<Apple> inventory){ List<Apple> result = new ArrayList<>(); for (Apple apple : inventory) { if (apple.getWeight() > 150) { result.add(apple); } }}

在java8中,可以这么实现:

public static boolean isGreenApple(Apple apple) { return "green".equals(apple.getColor());}public static boolean isHeavyApple(Apple apple) { return apple.getWeight() > 150;}public interface Predicate<T>{ boolean test(T t);}static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p) { List<Apple> result = new ArrayList<>(); for (Apple apple : inventory) { if (p.test(apple)) { result.add(apple); } } return result;}// 使用filterApples(inventory, Apple::isGreenApple);filterApples(inventory, Apple::isHeavyApple);

如果你觉得这么用太麻烦了,也可以使用以下方式:

filterApples(inventory, (Apple a) -> "green".equals(a.getColor()));filterApples(inventory, (Apple a) -> a.getWeight() > 150);

标签: #java参数化