考虑下表:
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 (使用字符串数组作为值,双倍作为键)进行排序,然后按值进行排序,但我忽略了按名称排序。
Map<Double, String[]> map = new HashMap<Double, String[]>();
map.put(5.0, {"Mike", "x6"});
System.out.println(map.get(5.0));我不知道存储数据的最好方法是什么。我还想知道Java 8中的解决方案。
发布于 2015-08-25 13:10:15
首先,您应该使表的每一行成为一个对象:
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用于在唯一键和值之间创建链接。每个数字与名称和代码相关联是否有意义?
一旦您拥有了这个对象,根据它的属性对其进行排序就更容易了:
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());发布于 2015-08-25 13:02:29
我认为Map对于您的情况是错误的数据结构,因为Maps显式地没有根据值定义订单。
但你可以在溪流中自救。类似于:
map.entrySet().stream().sorted((e1, e2) -> e1.getValue()[0].compareTo(e2.getValue()[0])).map(e -> e.getKey()).toArray(l -> new Integer[l])这将为您提供一个按值数组中的第一个整数排序的键数组。然后,您可以在原始地图中查找完整的值。
https://stackoverflow.com/questions/32204594
复制相似问题