ArrayList <integer>中的Java自定义类型的Integer对象

时间:2018-09-06 07:11:58

标签: java sorting arraylist integer

我有一个包含以下数字的ArrayList:

[6902, 6903, 6904, 790, 10902, 10903, 10904, 1190, 7901, 7902, 7903, 7904, 8904
, 990, 9901, 9902, 890, 8901, 8902, 8903, 6503, 6504, 690, 6901, 12904, 1310, 1
3101, 13102, 13103, 13104, 9903, 9904, 1090, 10901, 1290, 12901, 12902, 12903, 
11901, 11902, 11903, 11904, 5903, 5904, 590, 5901, 5902, 650, 6501, 6502]

现在,Collections.sort的自然顺序将是590、650、690,依此类推。 但是我需要订购590、5901、5902、5903、5904、650、6501、6502、6503 ...

是否有一种优雅的方法来做到这一点?还是我必须iterateArrayList才能进行许多if / elseifs的排序?

3 个答案:

答案 0 :(得分:3)

使用Collections.sort(List, Comparator)并提供自己的比较器,以给出所需的顺序。

答案 1 :(得分:1)

因为我认为您希望按照字典顺序对值进行排序,所以您所要做的就是使用比较器将两个项目都转换为字符串。

list.sort(Comparator.comparing(Object::toString));
System.out.println(list);
  

[1,1090,10901,10902,10903,10904,1190,11901,11902,11903,11904,1290,12901,12902,12903,12904,1310,13102,13103,13104,3101,590,5901, 5902、5903、5904、650、6501、6502、6503、6504、690、6901、6902、6903、6904、790、7901、7902、7903、7904、890、8901、8902、8903、8904、990、9901, 9902、9903、9904]

答案 2 :(得分:0)

您可以使用Comparator界面来实现此目的。
创建一个实现Comparator接口的类

class compareInt implements Comparator<Integer>{

    public int compare(Integer a, Integer b)// Override This method as your need
        {
           return 0; //should -1,0 or 1 to sort Integers
        }
    }

使用此链接可了解有关Comparator方法的更多信息:https://www.geeksforgeeks.org/comparator-interface-java/