java中对一组数据根据某一具体属性进行排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/clever_wr/article/details/88982798

不得不说java 8的特性真的很强大,java 8是基于函数式编程。具体使用的版本就是:

$ java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)

函数式编程具体的好处例如以下排序操作:

Lsit<student> students = new Arraylist<student>(); 
...(一系列对students的赋值操作)
Collections.sort(students, (s1, s2) -> s1.compareTo(s2));//使用函数式变成对list中的student类进行排序。

其中Stream具有的Collector真的很强大。Collector是Stream的可变减少操作接口,可变减少操作包括:将元素累积到集合中,使用StringBuilder连接字符串;计算元素相关的统计信息,例如sum,min,max或average等。Collectors(类收集器)提供了许多常见的可变减少操作的实现。

具体实际例子:

1.首先定义一个student类:

public class student {
    private String name;
    private int age;
    private int score;
    //constructors, getter/setters
}

然后对应main 函数部分和实际操作部分:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class example {
    public static void main(String[] args) {
        List<student> students = Arrays.asList(
                new student("alice", 10, 50),
                new student("bob", 20, 100),
                new student("alice", 10, 80),
                new student("alice", 10, 40),
                new student("aliy", 20, 70),
                new student("aliy", 20, 90),
                new student("alice", 10, 98),
                new student("aliy", 20, 77)
        );
        Map<String, Long> counting = students.stream().collect(
                Collectors.groupingBy(students::getName, Collectors.counting()));
        System.out.println(counting); 
        Map<String, Integer> sum = students.stream().collect(
                Collectors.groupingBy(student::getName, Collectors.summingInt(student::getScore)));//根据名字进行groupby操作
        System.out.println(sum);
 
    }
}

猜你喜欢

转载自blog.csdn.net/clever_wr/article/details/88982798
今日推荐