Iterating through a LinkedHashMap in reverse order

后端 未结 6 657
粉色の甜心
粉色の甜心 2020-11-28 12:06

I have a LinkedHashMap:

LinkedHashMap

that I need to iterate through from a given key\'s position, backwar

6条回答
  •  时光说笑
    2020-11-28 12:29

    This is an old question, but I think it's lacking an answer that takes a newer approach. The following uses Java 9 features:

    Deque> top = map.entrySet().stream()
            .takeWhile(e -> !givenKey.equals(e.getKey()))
            .collect(Collectors.toCollection(ArrayDeque::new));
    

    The code above streams the map's entryset, keeping entries until a key equal to the given key is found. Then, the entries are collected to an ArrayDeque.

    One detail is missing, though. Depending on whether you need the entry that matches the given key to also be included in the result or not, you might need to manually add it to the deque. If you don't want it added, then you're done. Otherwise, simply do:

    top.add(Map.entry(givenKey, map.get(givenKey)));
    

    Now, to iterate the Deque in reverse order, simply use its descendingIterator():

    Iterator> descIt = top.descendingIterator();
    

    It's worth mentioning that this approach only works if the stream is sequential. Anyways, we wouldn't have gained anything using a parallel stream here.

提交回复
热议问题