Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a limited number of values from a HashMap or LinkedHashMap?

Say I have a LinkedHashMap containing 216 entries, how would I get the first 100 values (here, of type Object) from a LinkedHashMap<Integer, Object>.

like image 697
Adnan Ali Ch. Avatar asked Jan 21 '26 14:01

Adnan Ali Ch.


1 Answers

Well to start with, doing this for HashMap as per your title, doesn't make much sense - HashMap has no particular order, and the order may change between calls. It makes more sense for LinkedHashMap though.

There, I'd use Guava's Iterables.limit method:

Iterable<Object> first100Values = Iterables.limit(map.values(), 100);

or

// Or whatever type you're interested in...
Iterable<Map.Entry<Integer, Object>> firstEntries =
    Iterables.limit(map.entrySet(), 100);

You can then create a list from that, or iterate over it, or whatever you want to do.

like image 128
Jon Skeet Avatar answered Jan 23 '26 02:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!