Lavish Khetan
Lavish Khetan

Reputation: 59

Sort and Compare LinkedHashMap and fetch 3 elements

There is a Json which has many attributes named id, I have to sort that, then compare and then I have to fetch the recently added 3 Objects with id as an attribute.

restgetAllRecentOrders: fetches all the recent orders

        List<LinkedHashMap> recentOrders = restCalls.restgetAllRecentOrders();
        if (recentOrders.size() > 0) {
            int recentOrder1Id = (int) ((LinkedHashMap) (recentOrders.get(recentOrders.size() - 1))).get("id");
            recentOrders.sort((LinkedHashMap o1, LinkedHashMap o2) -> ((Integer) o1.get("id")).compareTo((Integer) o2.get("id")));

I am not able to understand how i can fetch three objects, after sorting and then comparing them on the basis of id's

Upvotes: 0

Views: 69

Answers (1)

Chris
Chris

Reputation: 458

Let's assume

JSON:

[{
  id=1,
  name=name one,
  desc=description one
}, {
  id=4,
  name=name four,
  desc=description four
},{
  id=3,
  name=name three,
  desc=description three
}, {
  id=2,
  name=name two,
  desc=description two
}, {
  id=0,
  name=name zero,
  desc=description zero
}]

JAVA:

List<Integer> recent3 = recentOrders.stream().map(m -> (int) m.get("id")).sorted().skip(Math.max(recentOrders.size() - 3, 0)).collect(Collectors.toList());

Upvotes: 1

Related Questions