Need help with creating a hashset and selecting distinct sorted data

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • elpeak
    New Member
    • Jul 2007
    • 2

    #1

    Need help with creating a hashset and selecting distinct sorted data

    I read in a text file to created a hashmap based on the users id which is unique. This works fine, however, I also need to extract the users name, but I only need the name once and sorted. I am trying to do this with a hashset with some success. I can get the data but there are duplicates and it's not sorting. I thought the hashset would do this automatically.

    Is it possible to extract this data into a hashset from the hashmap as describe above? I've put a sample of hashmap.

    Code:
    HashMap value = new HashMap();
        /** Creates new form TestHashMap */
    
    
    
    
    
      public void fileRead() throws Exception
      {
    
                    FileReader fr = new FileReader("C://Documents and Settings//epeak//My Documents//test.txt");
    		BufferedReader br = new BufferedReader(fr);
    		String s;
    		while((s = br.readLine()) != null) {
    		Pattern p = Pattern.compile("[\\s]+");
    		String[] str = p.split(s);
    
    //		System.out.println(str[0] + " "+str[1] +"   "+str[2]+"   "+str[3]);
                     Propertyunbuf prop = new Propertyunbuf();
    		 prop.setPropertyId(str[0]);
    		 prop.setPropertyName(str[1]);
                     prop.setPropertyValue( new Double(str[2]));
    //		 prop.setPropertyValue(new Double(str[2]).doubleValue());
    		 prop.setAgendId(str[3].trim());
    //                 System.out.println(str[1]);
    
    
    
     HashSet ref = new HashSet(); // create a HashSet
    		 Iterator i = ref.iterator(); // get iterator
    
    		 System.out.println( "\nNonduplicates are: " );
    		 while ( i.hasNext() )
    			 System.out.print( i.next() + " " );
    
    		 System.out.println();
    Last edited by Frinavale; Sep 2 '10, 03:12 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    @elpeak,

    First off, please use code tags. There's a FAQ page that might help you here.

    Second, not to nit pick, but you really should qualify your generic containers - it really helps keep things straight when projects grow. There is little worse than trying to figure out what exactly is in that map you just got from a method with no other significant documentation.

    Here is a method that I wrote to give a sorted list of the keys from a HashMap, which compiles...
    Code:
      private void merple()
      {
        java.util.HashMap<String, Object> map = new java.util.HashMap<String, Object>();
        java.util.ArrayList<String> array = new java.util.ArrayList<String>();
        array.addAll(map.keySet());
        java.util.Collections.sort(array);
      }

    Comment

    Working...