按多列排序,Java 8 [英] Sort by multiple columns, Java 8

查看:116
本文介绍了按多列排序,Java 8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下表:

Name Code Number
Mike x6   5.0
Mike b4   3.0
Mike y2   1.0
Tom  y2   4.5
Tom  x6   4.5
Tom  b4   1.0
Susi x6   4.0
Susi y2   3.0
Susi b4   2.0

我有三列,应首先按名称列排序,然后按列排序数。我想用Dictionary做这个(使用String数组作为值,Double作为键),然后按值排序,但我想念按名称排序。

I have three columns, it should be sorted first of all by the column "Name" and then by the column "Number". I wanted to do this with Dictionary (use String array as value and Double as key) and then sort by value, but I miss the sort by the name.

Map<Double, String[]> map = new HashMap<Double, String[]>();
map.put(5.0, {"Mike", "x6"});
System.out.println(map.get(5.0));

我不知道存储数据的最佳方式是什么。我也想知道Java 8中的解决方案。

I don't know what is the best way to store my data. I would like also to know the solution in Java 8.

推荐答案

首先,你应该让你的每一行都成为一个对象:

First of all, you should make each line of your table an object:

public class MyData {

    private String name;
    private String code;
    private Double number;

    public MyData(String name, String code, Double number) {
        this.name = name;
        this.code = code;
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public String getCode() {
        return code;
    }

    public Double getNumber() {
        return number;
    }

}

使用 Map< Double,String []> 并不代表您要实现的目标。 Map 用于在唯一键和值之间创建链接。将每个数字与名称和代码相关联是否有意义?

Using Map<Double, String[]> does not represent what you are trying to achieve. A Map is used to create a link between an unique key an a value. Does it make sense for each number to be associated to a name and a code?

一旦有了这个对象,就可以根据它的属性对它进行排序要容易得多:

Once you have this object, it is much easier to sort it according to its properties:

List<MyData> list = new ArrayList<>();
list.add(new MyData("Mike", "x6", 5.0));
list.add(new MyData("Mike", "b4 ", 3.0));
list.add(new MyData("Mike", "y2", 1.0));
list.add(new MyData("Tom", "y2", 4.5));
List<MyData> sortedList = list.stream()
                              .sorted(Comparator.comparing(MyData::getName).thenComparing(MyData::getNumber))
                              .collect(Collectors.toList());

这篇关于按多列排序,Java 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆