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>
.
This ugly one-liner would do (and return a ArrayList<Object>
in the question's case):
Collections.list(Collections.enumeration(lhMap.values())).subList(0, 100)
This would work for a HashMap
as well, however HashMap
being backed by a HashSet
there's not guarantee that you will get the first 100 values that were entered; it would work on other types, with similar limitations.
Notes:
(as per the OP's comment)
Map<Integer, Pair<Double, SelectedRoad>> hashmap3 =
new LinkedHashMap<Integer, Pair<Double, SelectedRoad>>();
// [...] add 216 elements to hasmap3 here somehow
ArrayList<Pair<Double,SelectedRoad>> firstPairs =
Collections.list(Collections.enumeration(hashmap3.values())).subList(0, 100)
// you can then view your Pairs' SelectedRow values with them with:
// (assuming that:
// - your Pair class comes from Apache Commons Lang 3.0
// - your SelectedRoad class implements a decent toString() )
for (final Pair<Double, SelectedRoad> p : firstPairs) {
System.out.println("double: " + p.left);
System.out.println("road : " + p.right);
}