0

I have a List whose contents are Map with string keys and values if type String or Long.

[{
  "name": "Abc",
  "id": 1522047548000
},
{
  "name": "Xyz",
  "id": 1522048221000
}]

How can I sort the list

  1. based on id which is long
  2. based on name which is String
user8765332
  • 85
  • 3
  • 9
  • Reformulate your question, I don't understand it. `{name,id}` is the value? And what is the key? – anat0lius Apr 04 '18 at 07:15
  • @anat0lius keys are always string type but value is string type for name and long type for id. I want to sort based on id – user8765332 Apr 04 '18 at 07:27

2 Answers2

3

Since JAVA 1.8 there is new method in java.util.Comparator called comparing. It returns comparator comparing objects by given key. https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparing-java.util.function.Function-

In this case to compare by names it would look like:

 list.sort(Comparator.comparing(o -> String.valueOf(o.get("name"))));

and to compare by id:

 list.sort(Comparator.comparing(o -> (Long) o.get("id")));
A.K.
  • 103
  • 4
1

Using Java 8, you can dome something like this:

list.stream()
.sorted((a, b) -> a.get("id").compareTo(b.get("id"))
   .thenComparing(a.get("name").compareTo(b.get("name")));

The result is another stream, which you can collect into another list. This doesn't change the original list (which may or may not be useful).

(I'm new to Java, used to use C# the last couple of years, so I may have missed something ...)

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193