0

I need to convert a TreeMap to an array; could anyone show me how it's done? I need both keys and values.I am mapping each word to its frequency in a text file

Here is output :

Bypass Internet Censorship.txt

{about=1, administrators=1, ago=1, and=1, around=1, asking=1, at=2, blocked=1, by=1, com=1, device=1, either=1, filtering=1, freerk=1, get=1, helps=1, hope=1, i=1, long=1, not=1, or=2, remember=1, school=1, sites=1, so=1, some=1, someone=1, that=1, the=1, this=1, to=1, view=1, was=1, ways=1, web=1, were=1, work=1, www=1, zensur=1}
sum2000
  • 1,363
  • 5
  • 21
  • 36
  • what format do you need in arrays ? do you need a 2D array, or single dimension? surely you can iterate over the map and put the values into an array? also, why do you need an array ? – aishwarya Dec 19 '11 at 10:28
  • i need 2D array, i need to store them in an array to perform LSI – sum2000 Dec 19 '11 at 12:43
  • in that case, you may actually be better off with a map. Anyways, if you do need an array, use Sean's solution with Pangea's loop. – aishwarya Dec 20 '11 at 04:06

2 Answers2

2
    StringBuilder temp=new StringBuilder();

    for(Map.Entry<String,Integer> entry : treeMap.entrySet()) 
    {
      String key = entry.getKey();
      Integer value = entry.getValue();

      temp.append(key).append(" = ").append(value).append(", ");
    }

    //TODO remove the last comma

String result=temp.toString();
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
0

Don't use a TreeMap, use Guava's TreeMultiSet.

String[] str = new String[treeMultiSet.size()];
int ct = 0;
for(MultiSet.Entry<String> entry : treeMultiSet.entrySet()){
   str[ct++] = entry.getElement() + "=" + entry.getCount();
}

Update almost 10 years later:

I still think a MultiSet is better suited for the job, because the write path is much less painful, but here's a Java 8+ version of doing it with a Map (including TreeMap):

static String mapToArray(Map<String, Integer> map) {
    return map.entrySet()
              .stream()
              .map(e -> e.getKey() + "=" + e.getValue())
              .collect(Collectors.joining(", ", "{", "}"));
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • actually , i am new to java ,the code which i made is very long as it involves folders, files etc. , i would prefer now not to change code , can you tell me how to do it with TreeMap. – sum2000 Dec 19 '11 at 09:48
  • Why should we not use TreeMap? By the way, the link is dead. – Twonky Jul 28 '17 at 07:41