javaandroidhashmaplinkedhashmap

Reverse order of LinkedHashMap to LinkedHashMap or ArrayList


I have a LinkedHashMap<String,String> which looks something like this (don't really know how to illustrate a HashMap):

{
  "10/10/2010 10:10:10" => "SomeText1",
  "10/10/2019 10:10:19" => "SomeText2",
  "10/10/2020 10:10:20" => "SomeText3",
  "10/10/2021 10:10:21" => "SomeText4"
}

And I want to put it like this:

{
  "10/10/2021 10:10:21" => "SomeText4",
  "10/10/2020 10:10:20" => "SomeText3",
  "10/10/2019 10:10:19" => "SomeText2",
  "10/10/2010 10:10:10" => "SomeText1"
}

I have written this solution which works because the result I want is an ArrayList, but i was thinking if there was an easier way to reverse the LinkedHashMap maintaining the same type using a tool like sort for example.

private LinkedHashMap<String, String> map = new LinkedHashMap<>();
int sizeOfHashMap = map.size();
ArrayList reversedHashToArrayList = new ArrayList(map.size());
   for (Map.Entry<String,String> entry : map.entrySet()) {
   String key = entry.getKey();
   String value = entry.getValue();

   reversedHashToArrayList.add(0,entry);
}

Solution

  • A LinkedHashMap orders by insertion; it would be more logical to sort on the associated date time:

    private SortedMap<LocalDateTime, String> map = new TreeMap<>(Comparator.naturalOrder()
                                                                           .reversed());
    
    LocalDateTimeFormatter formatter = LocalDateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss");
    map.put(LocalDateTime.parse("10/10/2010 10:10:10", formatter), "...");
    

    To specify that the map is sorted, there is the interface SortedMap. Better use an interface, which is more versatile. The implementation class for a sorted map is the TreeMap. However you want a reversed comparison.

    You could use a Local specific pattern. Mind that above I chose Month/Day and not the British Day/Month.