Search code examples
javahashmaplinkedhashmap

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>.


Solution

  • Ugly One-Liner

    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:

    • relatively unefficient (read the Javadoc to know why - though there's worse!),
    • careful when using views (read the Javadoc to know more),
    • I did mention it was ugly.

    Step-By-Step Usage Example

    (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);
    }