Mira
Mira

Reputation: 17

Display first records in a sorted Map

I'm trying to display first 40 records out of 17K I have stored in a map. I have the following code

import java.util.*;
Map<String, Integer> doubleCount= new HashMap<String,Integer>(); 
....
Map<String,Integer> newDouble40 = doubleCount.headMap(40);

Java is giving me the following error:

" cannot find symbol - method subMap...

so I tried:

Map<String,Integer> newDouble40 = doubleCount.subMap("",(Integer)40);

and the exact error was: cannot find symbol - method subMap(java.lang.String,java.lang.int)

http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html how do I sort?

Upvotes: 1

Views: 319

Answers (2)

jbarrueta
jbarrueta

Reputation: 5185

Main issue here is that you're trying to use methods of a subinterface (java.util.SortedMap), the interface Map doesn't expose either headMap(...) or subMap(...) methods.

A correct code that will compile would be:

 SortedMap<String, Integer> doubleCount = new TreeMap<String, Integer>();

 Map<String, Integer> newDoubleCount = doubleCount.headMap("40");

One thing you should consider is what is that the methods of the SortedMap returns a portion of the map based on the key argument, compared with the keys in the map, unless you know what is the value of the key of the 40th element, you can't use these methods.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

subMap() and headMap() are two methods in SortedMap those are not available in Map

You can try following way

 Map<String, Integer> doubleCount= new HashMap<String,Integer>();
 SortedMap<String, Integer> newMap= new TreeMap<>(doubleCount);
 Map<String,Integer> newDouble40 = newMap.subMap("0","40"); 

In your case Keys are String so you need to have String values in subMap("0","40"). 0 is the starting key and "40" is the ending key. Your newDouble40 has element which has a key in between 0 and 40.

Here you can use headMap() as newMap.headMap("40"). now you will get elements which has a key less than 40.

Eg:

 Map<String, Integer> doubleCount= new HashMap<>();
 doubleCount.put("c",1);
 doubleCount.put("d",2);
 doubleCount.put("a",1);
 doubleCount.put("b",4);
 SortedMap<String, Integer> newMap= new TreeMap<>(doubleCount);//sorted now
 Map<String,Integer> map1 = newMap.subMap("a", "c");
 Map<String,Integer> map2 = newMap.headMap("c");
 System.out.println(map1);
 System.out.println(map2);

Out put:

 {a=1, b=4}
 {a=1, b=4}

Upvotes: 4

Related Questions