【发布时间】:2020-07-07 01:02:11
【问题描述】:
我正在尝试按一些自定义顺序对自定义对象进行排序,但我做不到。如果对象是字符串或整数,我可以排序。我在下面的代码上发布了一些详细的描述。感谢您的帮助。
Private static final List<String> places = Arrays.asList(“Switzerland”, “America”, “Romania”, “Chad”, "Australia");
//this list is fixed and always needs to maintain this order
Map<String, String> countrFromDB = countryDAO.getAllCOuntriesFromDB();
List<Country> sortCountry= new ArrayList<>();
for(Map.Entry<String, String> entry : countrFromDB.entrySet() ){
Country c = new Country(entry.getKey(), entry.getValue());
sortCountry.add(c);
if(places.contains(countrFromDB.getKeyValue())){
sortCountry.add(c.getKeyValue());
}
}
for(Country data:sortCountry){
System.out.println(data.getKeyValue());
}
我收到America, Chad, Australia, Switzerland, Romania。但是,我需要像在
places = Switzerland, America, Romania, Chad, Australia
【问题讨论】:
-
发布国家类以及显示每个国家/地区的键值的数据集
-
“没有任何工作”不是一个足够好的问题描述。是编译器错误吗?行为错误?
getKeyValue返回什么? -
@M.Prokhorov 它返回国家名称,我得到输出,但它没有排序。
-
@user10806781,那么我无法用给定的代码重现您的问题。对我来说,它以相反的词汇顺序输出国家名称,就像你的
Comparator说的那样:[Switzerland, Romania, Chad, Australia, America]。在您的问题中添加minimal reproducible example,并包含所有必要的数据,以便运行代码重现问题。 -
@M.Prokhorov 我认为我的比较器没有按照我想要的方式排序,这就是我发布这个问题的原因。我不想要反向词汇顺序,我的代码“位置”中有一个固定列表 - 排序应该始终保持该顺序。感谢您的努力
标签: java list spring-mvc