使用集合对值进行排序 [英] Using Collections to sort values

查看:69
本文介绍了使用集合对值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Collections进行排序很漂亮,对我来说,比使用Comparator更好,因为我有多个相同的值,并且我希望它们不会被扔掉。但是Collections有其自身的问题,似乎认为2+组的重复次数小于其实际较小的计数器部分

Using Collections to sort is nifty, a lot better for me than using Comparator since i have multiple values that are the same and i'd rather them not be just thrown out to the trash. But Collections has it's own issue, it seems to think repeating numbers of groups of 2+ to be smaller than their actual smaller counter parts

示例包含这些键和值( katy 1, mark 9, john 2, alice 11, josiah 22, chris 44),并将其排序如下

Example have these keys and values("katy 1","mark 9","john 2","alice 11","josiah 22","chris 44") and it sorts them as follows

爱丽丝11
凯蒂1
约翰2
约瑟亚22
克里斯44
马克9

alice 11 katy 1 john 2 josiah 22 chris 44 mark 9

正确的订单
凯蒂1
约翰2
马克9
爱丽丝11
约西亚22
马克44

Instead of the correct order katy 1 john 2 mark 9 alice 11 josiah 22 mark 44

我该如何解决?

推荐答案

由于您正在传递字符串,因此该集合无法告诉您想要的方式这些字符串将被解释(即按字符串中存在的数字排序)。您必须更加明确。

Since you are passing strings, the collection has no way of telling how you want these strings to be interpreted (i.e. sort by the number present inside the string). You must be more explicit.

基本上您有两个选择:

选择1 :创建一个新的数据类型以封装名称和数字并按数字进行比较:

Option 1: Create a new data type to encapsulate a name and a number and implement comparison by number:

public class Person implements Comparable<Person> {

     private String name;
     private int number;

     public Person(String name, int number) {
         this.name = name;
         this.number = number;
     }

     public int compareTo(Person p) {
         return this.number.compareTo(p.number);
     }
}

然后:

 List<Person> persons = new ArrayList<Person>();
 persons.add(new Person("alice", 11));
 persons.add(new Person("katy", 1));
 // etc.
 Collections.sort(persons);

选项2 :将字符串转换为键值对并放入它放在 TreeMap 内,该值自动按键对值进行排序:

Option 2: Turn the string into a key-value pair and put it inside a TreeMap, which automatically keeps the values sorted by key:

 TreeMap<Integer, String> map = new TreeMap<Integer, String>();
 map.put(11, "alice");
 map.put(1, "katy");
 // etc.

这篇关于使用集合对值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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