Skip to content
Advertisement

Sorting a List of Maps dynamically in Ascending and Descending order

I am having Maps inside a List.

I need to sort the List based on the input dynamically by passing it as a parameter into the method sortData.

It is working as expected, but the problem is that am not able to sort the list in reverse order.

I’m getting an Error : The method get(String) is undefined for the type Object

Code

JavaScript

Map 1 After sorting

JavaScript

Map 2 After sorting

JavaScript

Map 3 After sorting

JavaScript

Advertisement

Answer

Firstly, it’s worth to point out at some important issues with the code you’ve provided :

  • As I’ve said, it’s not a good practice to use Object as generic type. Generics were introduced to enforce the type safety, using Object as generic type is as bad as don’t use generics at all.
  • Don’t store the elements of different types together in a single collection. And avoid instanceof checks and type casting.
  • Don’t write your code against concrete classes like LinkedHashMap – variable type has to be Map instead.

You can find more elaborate explanation on all account mentioned above on this site if you doubt if these suggestions have a value.

With regard to your question, comparators as defined in your’r code will not compile.

That’s you can fix it:

JavaScript

When you’re chaining the methods, the compiler is unable to infer the type of the prameter o inside the comparing based on the type of the elements of the stream.

Parameter o is treated not as a Map but as Object therefore you can’t invoke get() on it.

Generic type information needs to be provided explicitly: <Map<String, Object>, String>. Where the first part – type of the argument passed into comparing (i.e. element of the stream), the second is a type of value that will be used for comparison (i.e. string).

for information on the syntax of generic methods, take a look at this tutorial

Advertisement