Java8特性:函数接口和集合操作

Java8特性:函数接口和集合操作

Function

  1. 简单函数

Function类似于数学中的函数:

y=f(x)

输入时x,输出是y,函数关系是f

Java8中的函数的写法类似于lambda表达式:

Function<Integer, Integer> f = x -> x + 5;
int y = f.apply(7);//y = f(7)

等价于数学函数:

y=f(x)=x+5

  1. 复合函数

对于一些复合函数,Function提供compose方法,其接受一个Function作为参数,类似数学中的函数:

y=f(x)z=g(y)z=g(f(x))

Function<Integer, Integer> f = x -> x + 5;
Function<Integer, Integer> g = y -> y * y;
Function<Integer, Integer> z = g.compose(f);
Function<Integer, Integer> z1 = g.andThen(f);//用g(x)的输出作为f的输入
System.out.println(z.apply(7));//输出144
System.out.println(z1.apply(7));//输出54

等价于数学函数:

z=g(f(x))=(x+5)2z1=f(g(x))=x2+5

groupBy操作

对于一个Map类型,我们需要对其values进行groupBy操作。

例如:

我们有一堆学生的数据grades如下:我们需要按照成绩等级进行groupBy

学号 等级
1 A
2 B
3 A
4 C
5 A
6 B
Map<String, String> grades = new HashMap(){
    {
        put("1", "A");
        put("2", "B");
        put("3", "A");
        put("4", "C");
        put("5", "A");
        put("6", "B");
    }
};

java8的集合操作、方法引用等新特性,下面一行代码便可以实现这个需求:

Map<String, List<String>> stat = grades.entrySet().stream().collect(Collectors.groupingBy(
            Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));

输出:

{A=[1, 3, 5], B=[2, 6], C=[4]}

如果采用其他的方法,我们可能需要先用一个Set存values,然后再按照values遍历整个map,然后放进另一个map,我们可能需要写很多for循环代码。

原文地址:https://www.cnblogs.com/Spground/p/9567868.html