Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java对象列表按未排序的特定对象排序_Java_Json_Java 8 - Fatal编程技术网

Java对象列表按未排序的特定对象排序

Java对象列表按未排序的特定对象排序,java,json,java-8,Java,Json,Java 8,我有下面的JSONArray,我正在尝试对它进行排序。因此,我将JSONArray转换为ArrayList,然后对它们进行排序并转换回JSONArray 请查找初始JSONArray(不按排序顺序) 请找到我下面的代码,它正在将我的JSONArray转换为ArrayList并对它们进行排序 Item item=null; List<Item> newItemList = new ArrayList<Item>(); for (int i=0;i<resultJSON

我有下面的JSONArray,我正在尝试对它进行排序。因此,我将JSONArray转换为ArrayList,然后对它们进行排序并转换回JSONArray

请查找初始JSONArray(不按排序顺序)

请找到我下面的代码,它正在将我的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
Item----->TE-7000-8003S
Item----->TE-7000-8003-K
Item----->TE-7000-8003-W
Item----->TE-7000-8003-WK

当您创建一个流并使用sorted时,您不会更改实际列表。因此,您可以执行以下操作:

List<Item> sortedItemList =newItemList
.stream()
.sorted((object1, object2) -> object1.getCode().compareTo(object2.getCode()))
.collect(Collectors.toList());
您可以使用
Comparator.comparing(Item::getCode)
来替换比较器

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

使用一个简单的
比较器
像这样应用于您的列表

newItemList
.sort((firstObj, secondObj) -> firstObj.getCode().compareTo(secondObj.getCode()));
或者更简单

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

您没有将排序操作的结果分配给任何对象。因此,您正在打印原始列表,而不是已排序的列表。如果要就地排序,只需使用list.sort()。使用newItemList.sort(您的比较器)对列表进行排序即可。比较器可以简化为
comparator。比较(Item::getCode)
Item::getCode不可能是比较器。您的意思可能是
Comparator.comparating(Item::getCode)
谢谢您的关注@JBNizet:)
newItemList
.sort(Comparator.comparing(Item::getCode));
newItemList
.sort((firstObj, secondObj) -> firstObj.getCode().compareTo(secondObj.getCode()));
newItemList.sort(Comparator.comparing(Item::getCode)); //dont forget to write getter method of Code variable.