Solved

displaying treeMap values in alphabetical using comparator

Posted on 2004-10-04
15
778 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jsp error 6 67
junit as external jar or library 7 55
maximize the sum of fractions 33 70
junit initializtion error 2 17
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…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

738 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