![](/img/trans.png)
[英]Java Sorting: sort an array of objects by property, object not allowed to use Comparable
[英]Java List of Objects sort by specific object which is not sorting
我有以下JSONArray試圖對它進行排序。 因此,為了將我的JSONArray轉換為ArrayList,然后對它們進行排序並轉換回JSONArray。
請找到最初的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",
}
]
請找到我的下面的代碼,它將我的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());
}
以下是輸出結果,而不是排序順序
Item----->TE-7000-8003-W
Item----->TE-7000-8003
Item----->TE-7000-8003-WK
Item----->TE-7000-8003S
Item----->TE-7000-8003-K
我期待如下結果:
Item----->TE-7000-8003
Item----->TE-7000-8003S
Item----->TE-7000-8003-K
Item----->TE-7000-8003-W
Item----->TE-7000-8003-WK
創建流並使用已排序時,不要更改實際列表。 所以你可以做到以下幾點:
List<Item> sortedItemList =newItemList
.stream()
.sorted((object1, object2) -> object1.getCode().compareTo(object2.getCode()))
.collect(Collectors.toList());
或者更好地使用sort方法對列表進行排序
newItemList
.sort((object1, object2) -> object1.getCode().compareTo(object2.getCode()));
並且您可以使用Comparator.comparing(Item::getCode)
來替換比較器
newItemList
.sort(Comparator.comparing(Item::getCode));
使用簡單的Comparator
就可以在您的列表中應用;
newItemList
.sort((firstObj, secondObj) -> firstObj.getCode().compareTo(secondObj.getCode()));
或者更簡單;
newItemList.sort(Comparator.comparing(Item::getCode)); //dont forget to write getter method of Code variable.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.