javalistsortinglambdajsonnode

How to sort List<jsonNode> alphabetically by a specific key using lambda .stream() in java


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.


Solution

  • 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.