ArrayList中整数对象的Java自定义排序<;整数>;

ArrayList中整数对象的Java自定义排序<;整数>;,java,sorting,arraylist,integer,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, 129

我有一个包含以下数字的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等等。 但我需要订购的是5909015902590359046506501603026503


有没有一种优雅的方法可以做到这一点,或者我必须在
数组列表上迭代
,并使用许多
if/elseif
,获得我想要的排序?

使用并提供您自己的比较器,给出您想要的顺序。

使用并提供您自己的比较器,给出您想要的顺序。

您可以使用比较器接口来实现这一点。
创建一个实现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
        }
    }
类compareInt实现Comparator{
public int compare(整数a,整数b)//根据需要重写此方法
{
返回0;//应-1,0或1对整数进行排序
}
}

使用此链接了解有关比较器方法的更多信息:

您可以使用比较器接口来实现此目的。
创建一个实现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
        }
    }
类compareInt实现Comparator{
public int compare(整数a,整数b)//根据需要重写此方法
{
返回0;//应-1,0或1对整数进行排序
}
}

使用此链接了解有关Comparator方法的更多信息:

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

list.sort(Comparator.comparing(Object::toString));
System.out.println(list);
[1、1090、10901、10902、10903、10904、1190、11901、11902、11903、11904、1290、12901、12903、12904、1310、13102、13103、13104、3101、590、5901、5902、5903、5903、5903、5904、5904、5904、5904、6502、6504、690、6901、6902、6903、6904、790、7901、7902、7903、7904、890、8901、8902、8903、8904、990、9901、9902、9903、9903、9904]


因为我认为您希望这些值按字典顺序排序,所以您所要做的就是使用comparator将这两个项转换为字符串

list.sort(Comparator.comparing(Object::toString));
System.out.println(list);
[1、1090、10901、10902、10903、10904、1190、11901、11902、11903、11904、1290、12901、12903、12904、1310、13102、13103、13104、3101、590、5901、5902、5903、5903、5903、5904、5904、5904、5904、6502、6504、690、6901、6902、6903、6904、790、7901、7902、7903、7904、890、8901、8902、8903、8904、990、9901、9902、9903、9903、9904]


你的排序逻辑是什么?似乎你想要字典顺序。将项目转换为
String
排序
ArrayList
最后返回
int
总有办法。转换为字符串,按字母顺序排序,再次转换为整数请添加一个相关的问题:和。您的排序逻辑是什么?您似乎想要按字典顺序排列。将项目转换为
String
排序
ArrayList
最后返回
int
总有办法。转换为字符串,按字母顺序排序,再次转换为整数请添加一个相关问题:和。