2

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);
}
4
  • 1
    Do you actually need the reversed LinkedHashMap? Wouldn't it be simpler to just iterate over it in reverse order where needed? Commented Jul 9, 2018 at 11:15
  • 2
    Any map is non-ordered structure. You can't expect any order from the map. It's only purpose is to store key-value pairs. The order of keys in a set can easily change in runtime, and you should never expect any order from the map Commented Jul 9, 2018 at 11:19
  • 3
    @VladyslavMatviienko well that's exactly why you use a LinkedHashMap which has a predictable iteration order... Commented Jul 9, 2018 at 11:20
  • @VladyslavMatviienko That's why I used a LinkedHasMap as Ben explained it Commented Jul 9, 2018 at 11:26

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If your motive is just to reverse the map ( show in descending order ) you can use Java.util.TreeMap.descendingMap() : It returns a reverse order view of the mappings contained in the map`

LinkedHashMap<String,String> map = .... //this is your intial hashmap
TreeMap<String,String> tmap = new TreeMap<>(map);
map.clear();
map.putAll(tmap.descendingMap());

This will do the trick.

Comments

0

Here Is My Own Written Logic for you. without using any built in functions to reverse:

 LinkedHashMap<String, String> map = new LinkedHashMap<>();
    map.put("10/10/2010 10:10:10", "SomeText1");
    map.put("10/10/2019 10:10:19", "SomeText2");
    map.put("10/10/2020 10:10:20", "SomeText3");
    map.put("10/10/2021 10:10:21", "SomeText4");

    LinkedHashMap<String, String> reversed = new LinkedHashMap<>();

    String[] keys = map.keySet().toArray(new String[map.size()]);

    for (int i = keys.length - 1; i >= 0; i--) {
        reversed.put(keys[i], map.get(keys[i]));
    }

6 Comments

Why not store in String[] it would avoid the bad toString()
Also using get(i) on any Linked map or list is generally something you want to avoid... This could be massively improved in many ways. You could use an iterator for starters
You can simply do System.out.println(reversed) and paste the result instead of a picture, if would be better
We are not downvoting, others do, please take in consideration our comment to improve your post (and your lvl)
It's a quite terribly inefficient solution, which is probably why it's receiving downvotes.
|
0

If you want to keep using a LinkedHashMap reversing it while keeping it somewhat efficient is not as easy. This is a solution that reverses a given LinkedHashMap using the iterator order (which is predictable for a LinkedHashMap and therefore probably what you are looking for).

Note that other solutions like using a SortedMap or a TreeMap are probably still better. Yet, for the sake of sticking to your original question, here is a solution:

public static <K, V> LinkedHashMap<K, V> reverse(LinkedHashMap<K, V> map)
{
    LinkedHashMap<K, V> reversedMap = new LinkedHashMap<K, V>();

    ListIterator<Entry<K, V>> it = new ArrayList<>(map.entrySet()).listIterator(map.entrySet().size());

    while (it.hasPrevious())
    {
        Entry<K, V> el = it.previous();
        reversedMap.put(el.getKey(), el.getValue());
    }

    return reversedMap;
}

Note that you won't get around wrapping the entry set into an ArrayList sadly as only that provides you with an ListIterator which can be initialized to any point other than the first element. Having something like a reverseIterator() method would simplify life a lot - sadly there is none available.

Complexity wise you iterate the list twice with this approach, first for the listIterator call from start to the last element and then once more from the back to the front when using previous. So you are looking at O(2n) here.

Comments

0

As of Java 21, the reversed() method on LinkedHashMap can be used to a reversed view of the map.

LinkedHashMap<String, String> map = ...;
LinkedHashMap<String, String> reversed = map.reversed();

This reversed view will be a SequencedMap. While it won't be a LinkedHashMap, it shares most characteristics with it (e.g. it is mutable, ordered, allows null).

If an ArrayList or LinkedHashMap are specifically needed, this reversed map can be converted to them in one of the many standard manners of converting a Map to one of those types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.