tl;dr
Map < Integer, Integer > myMap = Map.of ( 1 , 111 , 4 , 444 , 2 , 222 , 3 , 333 , 5 , 555 );
myMap.keySet().stream().sorted().limit( 3 ).map( key -> myMap.get( key ) ).forEach( System.out :: println ) ;
value: 111
value: 222
value: 333
Details
Focus on the keys first, filtering and sorting them.
Set< Integer > allKeys = myMap.keySet() ;
List< Integer > sortedKeys = new ArrayList<>( allKeys ) ;
Collections.sort( sortedKeys ) ;
Loop the first three keys, fetching the matching value from your map.
for ( int index = 0 ; index < 3 ; index++ )
{
Integer key = sortedKeys.get ( index );
Integer value = myMap.get ( key );
System.out.println ( "value: " + value );
}
See this code run live at IdeOne.com.
value: 111
value: 222
value: 333
Or truncate the list to the first three. You can call List::sublist
. Things to know:
- The new list is actually a view over a subset of original list. So the sub-list and original are tied together. To get a new separate list, we must feed the sub-list to a new list.
- The numbers passes to
subList
are annoying zero-based counting index numbers.
- The indexes are Half-Open, beginning is inclusive while the ending is exclusive.
Code.
List< Integer > targetKeys = new ArrayList< Integer >( sortedKeys.subList( 0 , 3 ) ) ;
Now loop the entire list of three elements.
for ( Integer targetKey : targetKeys )
{
Integer value = myMap.get ( targetKey );
System.out.println ( "value: " + value );
}
See this code run live at IdeOne.com.
value: 111
value: 222
value: 333
Or, get fancy with a one-liner using Java Streams.
Map < Integer, Integer > myMap = Map.of ( 1 , 111 , 4 , 444 , 2 , 222 , 3 , 333 , 5 , 555 );
myMap
.keySet ()
.stream ()
.sorted ()
.limit ( 3 )
.map ( key -> myMap.get ( key ) )
.forEach ( System.out :: println )
;
See this code run live at IdeOne.com.
value: 111
value: 222
value: 333