Search code examples
javahashsetsublistlinkedhashset

Get a sublist last 5 elements of LinkedHashSet?


Is there a one liner to get the last 5 elements of a LinkedHashSet in a new LinkedHashSet?

This is what I currently have, but it's not very efficient:

new LinkedHashSet<String>(new LinkedList<String>(set)
.subList(Math.max(0, set.size() - 5), set.size());

Or should I use for this case a TreeSet, SortedSet, HashSet ?


Solution

  • I ended up using this:

    com.google.common.collect.EvictingQueue<E>
    

    with this you get to keep only the last x elements.

    EvictingQueue<String> queue = EvictingQueue.create(5);