This is an old question, but I think it lacks an answer that requires a newer approach. The following uses Java 9 features:
Deque<Map.Entry<String, RecordItemElement>> top = map.entrySet().stream() .takeWhile(e -> !givenKey.equals(e.getKey())) .collect(Collectors.toCollection(ArrayDeque::new));
The above code streams a set of map entries, storing entries until a key equal to that key is found. Then the entries are collected in ArrayDeque .
One detail is missing though. Depending on whether you need an entry that matches the specified key to include in the result or not, you may need to manually add it to the queue. If you do not want this to be added, then everything is ready. Otherwise, just do:
top.add(Map.entry(givenKey, map.get(givenKey)));
Now, to Deque over Deque in reverse, just use its descendingIterator() :
Iterator<Map.Entry<String, RecordItemElement>> descIt = top.descendingIterator();
It is worth noting that this approach only works if the thread is sequential . In any case, we would not get anything using a parallel thread here.
Federico Peralta Schaffner Jan 21 '18 at 20:01 2018-01-21 20:01
source share