Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用集合对值进行排序_Java_Sorting_Collections_Compare - Fatal编程技术网

Java 使用集合对值进行排序

Java 使用集合对值进行排序,java,sorting,collections,compare,Java,Sorting,Collections,Compare,使用集合进行排序非常漂亮,对我来说比使用Comparator要好得多,因为我有多个相同的值,我不希望它们被扔进垃圾箱。但是集合有它自己的问题,它似乎认为2+组的重复数小于它们实际较小的计数器部分 示例中有这些键和值(“katy 1”、“mark 9”、“john 2”、“alice 11”、“josiah 22”、“chris 44”),并对它们进行如下排序 爱丽丝11 凯蒂1 约翰2 约西亚书22 克里斯44 马克9 而不是正确的顺序 凯蒂1 约翰2 马克9 爱丽丝11 约西亚书22 马克44

使用集合进行排序非常漂亮,对我来说比使用Comparator要好得多,因为我有多个相同的值,我不希望它们被扔进垃圾箱。但是集合有它自己的问题,它似乎认为2+组的重复数小于它们实际较小的计数器部分

示例中有这些键和值(“katy 1”、“mark 9”、“john 2”、“alice 11”、“josiah 22”、“chris 44”),并对它们进行如下排序

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

而不是正确的顺序 凯蒂1 约翰2 马克9 爱丽丝11 约西亚书22 马克44


如何解决这个问题?

最好的选择是重构代码,将字符串和整数分开

如果您不能或不想这样做,您必须提供自己的比较器。差不多

@Override
public int compare(String o1, String o2) {
    Integer i1 = Integer.parseInt(o1.replaceAll("[^0-9]", ""));
    Integer i2 = Integer.parseInt(o2.replaceAll("[^0-9]", ""));
    return i1.compareTo(i2);
}
然后你可以用

列表列表;//。。。
Collections.sort(list,newYourComparator());

您需要编写自己的比较器。如果要将字符串作为数字进行比较,则需要将其转换为数字。否则“22”<“4”,即使22>4


但是,我不知道如何使用默认的comparator获得第一个订单。

我认为必须创建实现Comparable接口的类Person

class Person implements Comparable<Person >{

       String name;
       Integer number;
       public int compareTo(Person o) {

        return number.compareTo(o.number);
    }

}
class-Person实现可比性{
字符串名;
整数;
公共内部比较(o人){
返回编号。比较(o.number);
}
}
检查此示例

编辑

public static void main(String arg[]){

    List<String> l = Arrays.asList(new String[]{"katy 1","mark 9","john 2","alice 11","josiah 22","chris 44"});

    Collections.sort(l, new Comparator<String>() {
        public int compare(String x, String y) {
            Integer a = Integer.parseInt(x.substring(x.indexOf(" ")).trim());
            Integer b = Integer.parseInt(y.substring(y.indexOf(" ")).trim());
            return a.compareTo(b);
        }
    });
    System.out.println(l.toString());
}
publicstaticvoidmain(字符串arg[]){
listl=Arrays.asList(新字符串[]{“katy 1”、“mark 9”、“john 2”、“alice 11”、“josiah 22”、“chris 44”});
Collections.sort(l,新的Comparator(){
公共整数比较(字符串x、字符串y){
整数a=Integer.parseInt(x.substring(x.indexOf(“”).trim());
整数b=Integer.parseInt(y.substring(y.indexOf(“”).trim());
返回a.compareTo(b);
}
});
System.out.println(l.toString());
}

由于您正在传递字符串,因此集合无法告诉您希望如何解释这些字符串(即,按字符串中的数字排序)。你必须更加明确

基本上有两种选择:

选项1:创建新的数据类型以封装名称和数字,并通过数字实现比较:

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);
     }
}
  • 将数据存储为
    映射
    ——不要将两种数据类型塞入一个字符串中
  • 将条目集放入列表并对其进行排序
  • 将已排序的条目集放入有序映射中
  • 下面是一些代码:

    public static void main(String[] args) {
        // Set up and load the map
        Map<String, Integer> nameAgeMap = new HashMap<String, Integer>();
        nameAgeMap.put("katy", 1);
        nameAgeMap.put("chris", 44);
        nameAgeMap.put("alice", 11);
        nameAgeMap.put("josiah", 22);
        nameAgeMap.put("john", 2);
    
        // Create-and-load a List of entries
        List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(nameAgeMap.entrySet());
        // Sort the list using a custom Comparator that compares the ages
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }});
    
        // Load the entries into a Map that preserves insert order
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> entry : entries)
            sortedMap.put(entry.getKey(), entry.getValue());
    
        // All done - let's see what we got
        System.out.println(sortedMap);
    }
    

    按升序对$value进行排序逻辑。如果您需要按降序排列,请交换变量i1和i2

    public static void main(String[] args) {
    
    
    
        List<String> l_oTestList = new ArrayList<String>();
        l_oTestList.add("$10000 - $12000");
        l_oTestList.add("$50 - $100");
        l_oTestList.add("$10000 - $12000");
        l_oTestList.add("$100 - $150");
        l_oTestList.add("$150 - $200");
        l_oTestList.add("$200 - $250");
        l_oTestList.add("$0 - $10");
        l_oTestList.add("$10 - $20");
        l_oTestList.add("$20 - $50");
        l_oTestList.add("$250 - $500");
        l_oTestList.add("$500 - $750");
        l_oTestList.add("$750 - $1000");
        l_oTestList.add("$1000 - $1250");
        l_oTestList.add("$1250 - $10000");
        List<String> l_oTestList1 = sort(l_oTestList);
        System.out.println(l_oTestList1.toString());
    }
    
    private static List<String> sort(List<String> pTestList) {
        Collections.sort(pTestList, new Comparator<String>() {
            public int compare(String o1, String o2) {
                Integer i1 = Integer.parseInt(o1.replace("$", "").substring(0,o1.indexOf("-")-2).trim());
                Integer i2 = Integer.parseInt(o2.replace("$", "").substring(0,o2.indexOf("-")-2).trim());
                return (i2 > i1 ? -1 : (i2 == i1 ? 0 : 1));
            }
        });
        return pTestList;
    }
    
    publicstaticvoidmain(字符串[]args){
    List l_oTestList=new ArrayList();
    l_oTestList.加上(“$10000-12000”);
    l_oTestList.加上(“$50-$100”);
    l_oTestList.加上(“$10000-12000”);
    l_oTestList.加上(“$100-$150”);
    l_oTestList.加上(“$150-$200”);
    l_oTestList.加上(“$200-$250”);
    l_oTestList.添加(“$0-$10”);
    l_oTestList.加上(“$10-$20”);
    l_oTestList.加上(“$20-$50”);
    l_oTestList.加上(“$250-$500”);
    l_oTestList.加上(“$500-750”);
    l_oTestList.加上(“$750-$1000”);
    l_oTestList.加上(“$1000-$1250”);
    l_oTestList.加上(“$1250-$10000”);
    列表l_oTestList1=排序(l_oTestList);
    System.out.println(l_oTestList1.toString());
    }
    私有静态列表排序(列表pTestList){
    Collections.sort(pTestList,newcomparator(){
    公共整数比较(字符串o1、字符串o2){
    Integer i1=Integer.parseInt(o1.replace(“$”,”).substring(0,o1.indexOf(“-”)-2.trim());
    Integer i2=Integer.parseInt(o2.replace(“$”,”).substring(0,o2.indexOf(“-”)-2.trim());
    返回(i2>i1-1:(i2==i1?0:1));
    }
    });
    返回pTestList;
    }
    
    为什么要把它弄得这么复杂?
    Integer
    类完全能够执行自己的comparison@JohanSj是的,你是对的。实际上我不知道,谢谢你澄清这个概念
     TreeMap<Integer, String> map = new TreeMap<Integer, String>();
     map.put(11, "alice");
     map.put(1, "katy");
     // etc.
    
    public static void main(String[] args) {
        // Set up and load the map
        Map<String, Integer> nameAgeMap = new HashMap<String, Integer>();
        nameAgeMap.put("katy", 1);
        nameAgeMap.put("chris", 44);
        nameAgeMap.put("alice", 11);
        nameAgeMap.put("josiah", 22);
        nameAgeMap.put("john", 2);
    
        // Create-and-load a List of entries
        List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(nameAgeMap.entrySet());
        // Sort the list using a custom Comparator that compares the ages
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }});
    
        // Load the entries into a Map that preserves insert order
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> entry : entries)
            sortedMap.put(entry.getKey(), entry.getValue());
    
        // All done - let's see what we got
        System.out.println(sortedMap);
    }
    
    {katy=1, john=2, alice=11, josiah=22, chris=44}
    
    public static void main(String[] args) {
    
    
    
        List<String> l_oTestList = new ArrayList<String>();
        l_oTestList.add("$10000 - $12000");
        l_oTestList.add("$50 - $100");
        l_oTestList.add("$10000 - $12000");
        l_oTestList.add("$100 - $150");
        l_oTestList.add("$150 - $200");
        l_oTestList.add("$200 - $250");
        l_oTestList.add("$0 - $10");
        l_oTestList.add("$10 - $20");
        l_oTestList.add("$20 - $50");
        l_oTestList.add("$250 - $500");
        l_oTestList.add("$500 - $750");
        l_oTestList.add("$750 - $1000");
        l_oTestList.add("$1000 - $1250");
        l_oTestList.add("$1250 - $10000");
        List<String> l_oTestList1 = sort(l_oTestList);
        System.out.println(l_oTestList1.toString());
    }
    
    private static List<String> sort(List<String> pTestList) {
        Collections.sort(pTestList, new Comparator<String>() {
            public int compare(String o1, String o2) {
                Integer i1 = Integer.parseInt(o1.replace("$", "").substring(0,o1.indexOf("-")-2).trim());
                Integer i2 = Integer.parseInt(o2.replace("$", "").substring(0,o2.indexOf("-")-2).trim());
                return (i2 > i1 ? -1 : (i2 == i1 ? 0 : 1));
            }
        });
        return pTestList;
    }