racecar
racecar

Reputation: 11

Sort response array in desc order in Java

I am trying to print the top 5 entries based on total.amount from an api response array.

The response looks something like this, but a lot longer:

[
    {
        "total": {
            "amount": "100000"
        },
        "name": {
            "first": "Test"
        },
    },
    {
        "total": {
            "amount": "500"
        },
        "name": {
            "first": "Test2"
        },
    }
]

At the moment I am able to print all the amount values in descending order:

public static void orderResultsDesc(int total) throws JSONException {
        JsonPath jsonPathValidator = response.jsonPath();
        List<String> totAm = jsonPathValidator.getList("total.amount");
        try {
            totAm.sort(Comparator.reverseOrder());
            System.out.println("List:\n" + totAm);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

But I need to adjust this to print the top 5 entries with a whole response (not just the total.amount values).

Have tried doing things like:

     List<Integer> ids = jsonPathValidator.getList("total.amount");
        for(Integer i:ids)
        {
            ids.sort(Comparator.reverseOrder());
            sortedOrder.add(ids); // this doesn't work
            System.out.println(i);
        }

It's new territory for me.. Any help is appreciated!!

Upvotes: 1

Views: 257

Answers (1)

Michel K
Michel K

Reputation: 411

One possible approach is to compute the indices of the five entries with the highest "total.amount". A possible implementation using streams:

import java.util.stream.Collectors;
import java.util.stream.IntStream;


List<String> amounts = jsonPath.getList("total.amount");
List<Integer> indices = 
        // Create stream of indices (integers from 0 to items.size()-1)
        IntStream.range(0, amounts.size()).boxed()
        // Sort indices by decreasing amount
        .sorted(Comparator.comparing(index -> Long.parseLong(amounts.get((int)index))).reversed())
        // We're only interested in the top five entries
        .limit(5)
        // Convert to list.
        .collect(Collectors.toList());

After that, you can iterate over these indices. To print the top five entries:

for (int index : indices) {
    System.out.println(jsonPath.getString("[" + index + "]"));
}

Upvotes: 1

Related Questions