简体   繁体   English

arraylist中的Java排序数字

[英]Java sort numbers in arraylist

I've created an arraylist like this 我已经创建了这样的arraylist

ArrayList<String> entries = new ArrayList<String>();
entries.add("0 - name1");
entries.add("1000 - name2");
entries.add("1004 - name4");
entries.add("1002 - name3");
entries.add("10000 - name5");
entries.add("2000 - name5");

The list always starts with a number between 0 and 15,000 so when i sort i would like it to just sort based on the number none of the numbers will ever match and they should be assorted in an ascending order. 该列表始​​终以0到15,000之间的数字开头,因此当我排序时,我希望它只根据数字进行排序,所有数字都不会匹配,它们应按升序排序。

How can this be done with java can i use a comparator? 如何使用java我可以使用比较器?

Yes, it can be done with a Comparator but it won't be very efficient because you will need to keep parsing the data to extract out the number and then you will need to convert the number to an Integer and do your comparison. 是的,可以使用比较器完成,但效率不高,因为您需要不断解析数据以提取数字,然后您需要将数字转换为整数并进行比较。

A better approach is to create a custom Object with two properties, number and name. 更好的方法是使用两个属性(数字和名称)创建自定义对象。 Then you can sort on the number. 然后你可以对数字进行排序。 The Comparator for this will be straight forward. 比较器将是直截了当的。 You can search the forum for examples. 您可以在论坛中搜索示例。

can i use a comparator? 我可以使用比较器吗?

yes, you can :) 是的你可以 :)

with syntax : Collections.sort(entries,comparator); 语法: Collections.sort(entries,comparator); - you need to import java.util.Collections and write comparator that makes what you want. - 你需要导入java.util.Collections并编写你想要的比较器。 You may as well try .sort(entries) using default comparator (but here it will not work :) ). 您也可以使用默认比较器尝试.sort(entries) (但这里不起作用:))。

here's complete solution: 这是完整的解决方案:

import java.util.Comparator;

public class MyComparator implements Comparator<String> {

    @Override
    public int compare(String arg0, String arg1) {

        int indexOf = arg0.indexOf("-");
        String substring = arg0.substring(0, indexOf-1);
        int indexOf1 = arg1.indexOf("-");
        String substring1 = arg1.substring(0, indexOf1-1);
        return Integer.valueOf(substring) - Integer.valueOf(substring1);
    }

}


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Runner {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<String> entries = new ArrayList<String>();
        entries.add("0 - name1");
        entries.add("1000 - name2");
        entries.add("1004 - name4");
        entries.add("1002 - name3");
        entries.add("10000 - name5");
        entries.add("2000 - name5");

        Comparator<String> comparator = new MyComparator();
        Collections.sort(entries, comparator );

        for (String e : entries){
            System.out.println(e);
        }

    }
}

Also - I strongly suggest to declare lists likes this: List<String> entries = new ArrayList<String>(); 另外 - 我强烈建议声明列表如下: List<String> entries = new ArrayList<String>(); Later you may find benefits of using LinkedList in place of ArrayList - then changing implementation of used list would be simplest possible. 稍后您可能会发现使用LinkedList代替ArrayList好处 - 然后更改使用列表的实现将是最简单的。

Plz google "Program to interface not to implementation". Plz谷歌“程序接口不实现”。 :) :)

Write a Comparator<String> that splits the inputs at - . 编写一个Comparator<String> ,将输入分成- Parse the first element with Integer.parseInt (trim if necessary). 使用Integer.parseInt解析第一个元素(必要时修剪)。 Than do the comparation with the refined integer values. 比做精细整数值的比较。
Code: 码:

class MyComp implements Comparator<String> {
     public int compare(String s1, String s2) {
           int v1 = Integer.parseInt(s1.split("-")[0]);
           int v2 = Integer.parseInt(s2.split("-")[0]);
           return v1 - v2;
     }

} }

Maybe you would like to try my number sorting algorithm: 也许您想尝试我的数字排序算法:

package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
    ArrayList<AffineTransform> affs;
    ListIterator<AffineTransform> li;
    Integer count, count2;
    /**
     * @param args
     */
    public static void main(String[] args) {
        new QuicksortAlgorithm();
    }
    public QuicksortAlgorithm(){
        count = new Integer(0);
        count2 = new Integer(1);
        affs = new ArrayList<AffineTransform>();
        for (int i = 0; i <= 128; i++){
            affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
        }
        affs = arrangeNumbers(affs);
        printNumbers();
    }
    public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
        while (list.size() > 1 && count != list.size() - 1){
            if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
                list.add(count, list.get(count2));
                list.remove(count2 + 1);
            }
            if (count2 == list.size() - 1){
                count++;
                count2 = count + 1;
            }
            else{
            count2++;
            }
        }
        return list;
    }
    public void printNumbers(){
        li = affs.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
    }
}

You could use the default comparator using Collections#sort provided that you use numbers of the form 01 and 02 and not 1 and 2 . 您可以使用集合#排序使用默认比较器,前提是您使用0102形式的数字而不是12

Otherwise you can create your own comparator, but I think @camickr suggestion to use a different representation is better. 否则你可以创建自己的比较器,但我认为@camickr建议使用不同的表示法更好。

How dependent are you upon that ArrayList? 您对ArrayList的依赖程度如何? I'm not so sure of your whole application, but the the "number - string" format of your ArrayList entries suggests to me that you actually need a Map here. 我不太确定你的整个应用程序,但是你的ArrayList条目的“数字 - 字符串”格式告诉我你实际上需要一个Map。 Implement this as a TreeMap and you get the sorting of the keys for free. 将其实现为TreeMap,您可以免费获得密钥的排序。

public static void main( String[] args ) {
    Map<Integer , String> map = new TreeMap<Integer , String>();
    map.put( 1, "name1" );
    map.put( 1000, "name2" );
    map.put( 1004, "name4" );
    map.put( 1002, "name3" );
    map.put( 10000, "name5" );
    map.put( 2000, "name5" );

    for ( Integer key : map.keySet() ) {
        System.out.println( String.format( "key: %d, value: %s", key, map.get( key ) ) );
    }
}

...produces... ... ...产生

key: 1, value: name1
key: 1000, value: name2
key: 1002, value: name3
key: 1004, value: name4
key: 2000, value: name5
key: 10000, value: name5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM