【问题标题】:Customized sorting of custom object [duplicate]自定义对象的自定义排序[重复]
【发布时间】: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


【解决方案1】:

你必须在比较器中使用indexOf

final List<String> places = Arrays.asList("Switzerland", "America", "Romania", "Chad", "Australia"); 
.....
.....
.....

Collections.sort(sortCountry, new Comparator<Country>(){
    public int compare(Country o1, Country o2){
        return places.indexOf(o1.getValue()) - places.indexOf(o2.getValue());
    }
});

for(Country data:sortCountry){
    System.out.println(data.getValue());
}

【讨论】:

  • 我在试试,看看效果如何
  • 最终你需要和indexOf一起玩@Joe是答案,老实说我不会花更多时间在这上面:) :)
  • 谢谢,老实说,你需要在 return 语句中调整 -1 0 和 +1 的代码,试试看
  • 那个比较器不遵循契约。如果第一个参数是Switzerland,它将报告任何元素的顺序相同,并且如果列表根本不包含o1,它只会报告o1 小于o2。你的意思是Comparator.comparingInt(o1 -&gt; places.indexOf(o1.getValue()))
  • 不,我没有想到任何代码,你是对的,places.indexOf 不会告诉 -1 +10 ,如果 compareInt 解决了,那么它应该是一个解决方案,甚至这段代码可以用一个偏移公式来形式化,它将返回 -1 +1 0 老实说我不想花更多时间:)
【解决方案2】:

为什么不首先按照你想要的顺序构建列表,这样你就不需要单独排序了?

List<Country> sortCountry= new ArrayList<>();
for(String place : places){
  if (countrFromDB.containsKey(place)) {
    Country c = new Country(place, countrFromDB.get(place));
    sortCountry.add(c);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    相关资源
    最近更新 更多