1

Below is the JsonNode which needs to be sorted alphabetically by key "size".

List<JsonNode> listOfSizes =[{"size":"CAL KING","SKU_ID":"68454463"},
                             {"size":"KING","SKU_ID":"68454456"},
                             {"size":"TWIN XL","SKU_ID":"68454425"},
                             {"size":"QUEEN","SKU_ID":"68454449"},
                             {"size":"FULL","SKU_ID":"68454432"},
                             {"size":"TWIN","SKU_ID":"68454418"}]

Expected result of sorting is :-

[{"size":"CAL KING","SKU_ID":"68454463"},
 {"size":"FULL","SKU_ID":"68454432"},
 {"size":"KING","SKU_ID":"68454456"},
 {"size":"QUEEN","SKU_ID":"68454449"},
 {"size":"TWIN","SKU_ID":"68454418"},
 {"size":"TWIN XL","SKU_ID":"68454425"}]

I tried doing below way:-

listOfSizes.stream().filter(sku -> NotEmpty(sku.get("size"))).sorted();  

It's not working. I also tried a couple more ways but didn't get expected result.

I am learning now lambda 8. Guys, please guide me if you know the exact logic for this because I do not want to do it in foreach way.

Abra
  • 19,142
  • 7
  • 29
  • 41
Pooja
  • 47
  • 6

1 Answers1

2

You can use the version of sorted that takes a Comparator:

List<JsonType> sortedBySize = listOfSizes.stream()
    .sorted(Comparator.comparing(jsonObject -> jsonObject.get("size"))
    .collect(Collectors.toList());

Can't tell what your JsonType is, so you would have to substitute that in.

midor
  • 5,487
  • 2
  • 23
  • 52
  • thank you so much! I tried the above code and replaced the JsonType to JsonNode but facing issue while doing .get() , its saying "The method get(String) is undefined for the type String" – Pooja Mar 30 '21 at 10:06
  • You would have to link to the JSON implementation you are using for me to answer this, but you can just check its documentation to see how to get a value from a JSON Object and use that method. One common pattern in JSON APIs is that they have different methods for different kinds of contained objects, i.e., `getNumber`, `getObject`, `getArray`, etc. – midor Mar 30 '21 at 10:19
  • Thank you , getting Expected result now !! – Pooja Mar 30 '21 at 10:27