The list of Java objects is sorted by specific objects, not by
•
Java
I have the following jsonarray trying to sort it So, to convert my jsonarray to ArrayList, then sort them and convert them back to jsonarray
Please find the original jsonarray (not in the sort order)
[ { "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 code below, which converts my jsonarray to ArrayList and sorts them
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()); }
The following is the output, not the sort order
Item----->TE-7000-8003-W Item----->TE-7000-8003 Item----->TE-7000-8003-WK Item----->TE-7000-8003S Item----->TE-7000-8003-K
I look forward to the following results:
Item----->TE-7000-8003 Item----->TE-7000-8003S Item----->TE-7000-8003-K Item----->TE-7000-8003-W Item----->TE-7000-8003-WK
Solution
Do not change the actual list when creating a stream and using sorted So you do cloud
List<Item> sortedItemList =newItemList .stream() .sorted((object1,object2) -> object1.getCode().compareTo(object2.getCode())) .collect(Collectors.toList());
Or better yet, use the sort method to sort the list
newItemList .sort((object1,object2) -> object1.getCode().compareTo(object2.getCode()));
And you can use comparator Comparing (item:: getcode) to replace the comparator
newItemList .sort(Comparator.comparing(Item::getCode));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码