Solved

displaying treeMap values in alphabetical using comparator

Posted on 2004-10-04
15
757 Views
Last Modified: 2009-07-29
what i would like to be able to do is to iterate through the map, use a comparator to compare the keys to see which one comes first in the alphabet.. so that when they are printed they come out in alphabetical order... all good said in theory but i realize with a map u can not simply iterate through... just after some ideas if any have some!
cheers

import java.io.*;
import java.util.*;

public class charCount
{
   
   
    public static void main(String[] args)
    {
        String sentence = "hello world";
       
        TreeMap tmap = new TreeMap();
       
        for (int i=0; i<sentence.length(); i++)
        {
            Character key = new Character(sentence.charAt(i));
            Integer oldCount = (Integer)tmap.get(key);
            Integer count = null;

            if (oldCount == null)
            {
                count = new Integer(1);
            }
            else
            {
                count = new Integer(oldCount.intValue() +1);
            }
            tmap.put(key, count);
       }
       
       
       
    }
}
0
Comment
Question by:ca_dyl
  • 7
  • 3
  • 3
  • +2
15 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12215859
Just use a TreeMap, then they will automatically
0
 

Author Comment

by:ca_dyl
ID: 12215877
cool so i dont have to use treeMap?? but then how do u print it to the console. for key & value...

sorry must be a total nuf nuf question but im only just starting :)

thx
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12215878
:-) You are anyway i see
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12215891
System.out.println(tmap);

Don't forget to *not* count spaces
0
 

Author Comment

by:ca_dyl
ID: 12215952
ok ok grasping all this slowly... last question i promise. I dont know how to get it so that the user can in put a string to be counted. Because at the mo i just used "hello world" so that i could check it workd, but how do i get user input?? i think i also fixed the space problemo.

thx

import java.io.*;
import java.util.*;

public class charCount
{
   
   
    public static void main(String[] args)
    {
        //charCount sentence = new charCount();
        //String sentence = new String();
        //String sentence = "hello world";
       
        TreeMap tmap = new TreeMap();
       
        for (int i=0; i<sentence.length(); i++)
        {
                if(i == ' ')
                {
                    return;
                }
                else
                {
                    Character key = new Character(sentence.charAt(i));
                    Integer oldCount = (Integer)tmap.get(key);
                    Integer count = null;
           
                    if (oldCount == null)
                    {
                        count = new Integer(1);
                    }
                    else
                    {
                        count = new Integer(oldCount.intValue() +1);
                    }  
                    tmap.put(key, count);
                }
   
       }
       
       System.out.println(tmap);
       
   
    }
}
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 12215971
String sentence = args[0]; // should check to ensure there *is* an args[0]
0
 
LVL 9

Expert Comment

by:Venci75
ID: 12215972
you can iterate through a map:
for (Iterator it = tmap.entrySet().iterator(); it.hasNext(); ) {
  Map.Entry entry = (Map.Entry)it.next();
  System.out.print(entry.getKey());
  System.out.print(" - ");
  System.out.println(entry.getValue());
}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 35

Expert Comment

by:girionis
ID: 12215974
> Because at the mo i just used "hello world" so that i could check it
> workd, but how do i get user input?? i think i also fixed the space problemo.

If you mean user input from the keyboard have a look here: http://javaalmanac.com/egs/java.io/ReadFromStdIn.html

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12215975
btw, you'll have to pass the sentence in in quotes or you'll only get one word
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12215992
i.e.

java charCount "the quick brown fox"
0
 
LVL 92

Expert Comment

by:objects
ID: 12216106
using an array instead of a map makes it alot simpler:

import java.io.*;
import java.util.*;

public class charCount
{
    public static void main(String[] args)
    {
        if (args.length>0)
        {
         String sentence = args[0];
         int[] count = new int[128];  // you can adjust this according to what characters you are interested in
       
         for (int i=0; i<sentence.length(); i++)
         {
             count[sentence.charAt(i)]++;
         }
        }      
    }
}
0
 
LVL 92

Expert Comment

by:objects
ID: 12216122
you can then loop thru the count array to determine the occurrences:

for (int i=0; i<count.length; i++)
{
   if (count[i]>0 && i!=' ')
   {
      System.out.println(((char)i)+" occurred "+count[i]+" times");
   }
}
0
 
LVL 92

Expert Comment

by:objects
ID: 12216129
as well as being simpler code its also more efficient than using a map.
0
 

Author Comment

by:ca_dyl
ID: 12216137
cheers guys you have been so much help :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12216179
8-)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now