简体   繁体   English

Java对象列表按特定对象排序,而不是排序

[英]Java List of Objects sort by specific object which is not sorting

Am having the following JSONArray which am trying to sort it. 我有以下JSONArray试图对它进行排序。 So, for that am converting my JSONArray into ArrayList then am sorting them and converting back into JSONArray. 因此,为了将我的JSONArray转换为ArrayList,然后对它们进行排序并转换回JSONArray。

Please find the initial JSONArray (which is not in sorting order). 请找到最初的JSONArray(不在排序顺序中)。

[  
   {  

      "code":"TE-7000-8003-W",
      "id":"13342",

   },
   {  
      "code":"TE-7000-8003",
      "id":"13163",
   },
   {  
      "code":"TE-7000-8003-WK",
     "id":"11573",
   },
   {  
      "code":"TE-7000-8003S",
      "id":"11565",

   },
   {  
      "code":"TE-7000-8003-K",
      "id":"11557",
   }
]

Please find my below code which am converting my JSONArray into ArrayList and sorting them. 请找到我的下面的代码,它将我的JSONArray转换为ArrayList并对它们进行排序。

Item item=null;
List<Item> newItemList = new ArrayList<Item>();
for (int i=0;i<resultJSONArray.length();i++) {
    JSONObject jobj = resultJSONArray.getJSONObject(i);
    item = new Item();
    item.setId(jobj.optString("id"));
    item.setCode(jobj.optString("code"));
    newItemList.add(item);
}

 newItemList
  .stream()
  .sorted((object1, object2) -> object1.getCode().compareTo(object2.getCode()));

Iterator<Item> itr = newItemList.iterator();
while(itr.hasNext()) {
    Item item1=itr.next();
    System.out.println("Item----->"+item1.getCode());
}

Following is the output am getting which is not sorted order 以下是输出结果,而不是排序顺序

Item----->TE-7000-8003-W
Item----->TE-7000-8003
Item----->TE-7000-8003-WK
Item----->TE-7000-8003S
Item----->TE-7000-8003-K

Am expecting the result like below : 我期待如下结果:

Item----->TE-7000-8003
Item----->TE-7000-8003S
Item----->TE-7000-8003-K
Item----->TE-7000-8003-W
Item----->TE-7000-8003-WK

When you create a stream and use sorted you don't change the actual list. 创建流并使用已排序时,不要更改实际列表。 So you could do the following: 所以你可以做到以下几点:

List<Item> sortedItemList =newItemList
.stream()
.sorted((object1, object2) -> object1.getCode().compareTo(object2.getCode()))
.collect(Collectors.toList());

or better sort the list with the sort method 或者更好地使用sort方法对列表进行排序

newItemList
.sort((object1, object2) -> object1.getCode().compareTo(object2.getCode()));

And you could use Comparator.comparing(Item::getCode) to replace the comparator 并且您可以使用Comparator.comparing(Item::getCode)来替换比较器

newItemList
.sort(Comparator.comparing(Item::getCode));

Use a simple Comparator to apply on your list just like that ; 使用简单的Comparator就可以在您的列表中应用;

newItemList
.sort((firstObj, secondObj) -> firstObj.getCode().compareTo(secondObj.getCode()));

Or more simple ; 或者更简单;

newItemList.sort(Comparator.comparing(Item::getCode)); //dont forget to write getter method of Code variable.

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

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