# Arrays vs HashMaps vs TreeSets - best method for sorting ability

• 05-24-2013, 07:27 PM
chiba
Arrays vs HashMaps vs TreeSets - best method for sorting ability
Hi guys,

I have written a program to rad in data and add it to a HashMap. The thing is now I want to sort it and I think it's not possible with HashMaps. I am also interested in adding a second piece of data.

Output is

Quote:

{Barton Bank=23660, Senor El Betrutti=25190, General Wolfe=17820, Dawn Run=26500, Uncle Ernie=15270, Alydar=22920, The Grey Monk=23120, Stalbridge Colonist=26620, Master Oats=22620, Assault=20290, Affirmed=17730, Poliantas=25130, Bobbyjo=25190, Lady Rebecca=18780, Lord Gyllene=19360, Rough Quest=20880, Norton's Coin=22460, Wayward Lad=23290, Young Kenny=20610, Afleet Alex=24860, Cab On Target=15320, Pridwell=20190, Voy Por Ustedes=22760}
I need to sort but the Integer value and it would be useful to add a count for each horse. Any ideas on the correct data structure?

Code:

```import java.io.File; import java.util.Hashtable; import java.util.Scanner; import java.util.Iterator; import java.util.HashSet; import java.util.HashMap; public class bets {         public static void main (String[] args)         {         File file = new File("horses.tsv");                 HashMap<String, Integer> race = new HashMap<String, Integer>();         boolean hexists;                         try             {                     Scanner scanner = new Scanner(file);                     String line = scanner.nextLine();                     int amount;                     String horse;                     String[] parts;                     while (line != null)                     {                     line = scanner.nextLine();                     parts = line.split("\t");                     horse=parts[0];                     hexists = race.containsKey(horse);                     amount=Integer.parseInt(parts[1]);                     if (hexists)                     {                             amount=race.get(horse)+amount;                             race.put(horse, amount);                     }                     else                     {                             race.put(horse, amount);                                                 }                     }                                 }             catch (Exception e)             {             //System.out.println(e);                     }             System.out.println(race);                              } }```
• 05-24-2013, 09:39 PM
jim829
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
Ok, let me try this again (I deleted an earlier post). You can use SortedMap and TreeMap to create a map which maintains sorted entries. Keys or values returned from keySet or values() will be in a sorted order based on the natural ordering of the elements.

Lists vs arrays. I tend to favor Lists because their more versatile and almost as efficient. Lists vs Maps. It depends on what you want to do. Lists are only indexed by ints and values must be added sequentially. With maps, you can use any object as a key and order is irrelevant.

Regards,
Jim
• 05-28-2013, 04:28 PM
chiba
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
Ok, so tried using a SortedMap as you suggested. I need the sort to be on the value though.

I suppose I could insert the data into a new SortedMap at the end using the value as the key instead of the horse name..

Code:

```import java.io.File; import java.util.*; public class sortedmap_bets {                 public static void main(String[] args)         {                 File file = new File("horses.tsv");                 SortedMap map = new TreeMap();                 boolean hexists;             try             {                     Scanner scanner = new Scanner(file);                 String line = scanner.nextLine();                 int amount;                 String horse;                 String[] parts;                                     while (line != null)                     {                     line = scanner.nextLine();                     parts = line.split("\t");                     horse=parts[0];                                         hexists = map.containsKey(horse);                     amount=Integer.parseInt(parts[1]);                     if (hexists)                     {                             amount=(int)map.get(horse)+amount;                             map.put(horse, amount);                     }                     else                     {                             map.put(horse, amount);                                                 }                     }             }             catch(Exception e)             {                     //System.out.println(e);                         }                   Iterator iterator = map.keySet().iterator();                   while (iterator.hasNext())                   {                   Object key = iterator.next();                   System.out.println("key : " + key + " value :" + map.get(key));                   }         } }```
Quote:

key : Affirmed value :17730
key : Afleet Alex value :24860
key : Alydar value :22920
key : Assault value :20290
key : Barton Bank value :23660
key : Bobbyjo value :25190
key : Cab On Target value :15320
key : Dawn Run value :26500
key : General Wolfe value :17820
key : Lady Rebecca value :18780
key : Lord Gyllene value :19360
key : Master Oats value :22620
key : Norton's Coin value :22460
key : Poliantas value :25130
key : Pridwell value :20190
key : Rough Quest value :20880
...

• 05-28-2013, 04:42 PM
jim829
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
Assuming you are using Integer values for your currency,

Code:

```SortedMap<String, Integer> bets = new TreeMap<>(); // Java 1.7 syntax //  or SortedMap<String, Integer> bets = new TreeMap<String, Integer>() // Java 1.5 and later. bets.put("Secretariat", 1000000);```
Regards,
Jim
• 05-28-2013, 05:53 PM
chiba
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
Code:

```import java.io.File; import java.util.Iterator; import java.util.Scanner; import java.util.SortedMap; import java.util.TreeMap; public class smap_bets {         public static void main(String[] args)         {                 File file = new File("horses.tsv");                 SortedMap<String, Integer> map = new TreeMap<>();                 boolean hexists;             int amount;             String horse;             String[] parts;                         try             {                     Scanner scanner = new Scanner(file);                 String line = scanner.nextLine();                                     while (line != null)                     {                     line = scanner.nextLine();                     parts = line.split("\t");                     horse=parts[0];                                         hexists = map.containsKey(horse);                     amount=Integer.parseInt(parts[1]);                     if (hexists)                     {                             amount=(int)map.get(horse)+amount;                             map.put(horse, amount);                     }                     else                     {                             map.put(horse, amount);                                                 }                     }             }             catch(Exception e)             {                     //System.out.println(e);             }             SortedMap<Integer, String> bets = new TreeMap<>();                         //add to a new SortedMap using the amount as key                   Iterator iterator = map.keySet().iterator();                   while (iterator.hasNext())                   {                           Object key = iterator.next();                           amount=map.get(key);                           horse=(String)key;                           bets.put(amount, horse);                   }                                     //print out                   iterator = bets.keySet().iterator();                   while (iterator.hasNext())                   {                           Object key = iterator.next();                           System.out.println(" £" +key + " " + bets.get(key));                   }         } }```
Quote:

£15270 Uncle Ernie
£15320 Cab On Target
£17730 Affirmed
£17820 General Wolfe
£19360 Lord Gyllene
£20190 Pridwell
£20290 Assault
£20610 Young Kenny
£20880 Rough Quest
£22460 Norton's Coin
£22620 Master Oats
£22760 Voy Por Ustedes
£22920 Alydar
£23120 The Grey Monk
£23660 Barton Bank
£24860 Afleet Alex
£25130 Poliantas
£25190 Senor El Betrutti
£26500 Dawn Run
£26620 Stalbridge Colonist

Now the amounts are sorted asc in order of amount
• 05-28-2013, 06:46 PM
chiba
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
That's what I wanted to do...

Code:

```import java.io.File; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.Scanner; import java.util.SortedMap; import java.util.TreeMap; public class smap_bets {         public static void main(String[] args)         {                 File file = new File("horses.tsv");                 //SortedMap<String, Integer> map = new TreeMap<>();                 NavigableMap<String, Integer> map = new TreeMap<String, Integer>();                 boolean hexists;             int amount;             String horse;             String[] parts;                         try             {                     Scanner scanner = new Scanner(file);                 String line = scanner.nextLine();                                     while (line != null)                     {                     line = scanner.nextLine();                     parts = line.split("\t");                     horse=parts[0];                                         hexists = map.containsKey(horse);                     amount=Integer.parseInt(parts[1]);                     if (hexists)                     {                             amount=(int)map.get(horse)+amount;                             map.put(horse, amount);                     }                     else                     {                             map.put(horse, amount);                                                 }                     }             }             catch(Exception e)             {                     //System.out.println(e);             }             //SortedMap<Integer, String> bets = new TreeMap<>();             NavigableMap<Integer, String> bets = new TreeMap<Integer, String>();                         //add to a new SortedMap using the amount as key                   Iterator iterator = map.keySet().iterator();                   while (iterator.hasNext())                   {                           Object key = iterator.next();                           amount=map.get(key);                           horse=(String)key;                           bets.put(amount, horse);                   }                                                             for (Map.Entry<Integer, String> e : bets.descendingMap().entrySet()) {                             System.out.println(e);                         }         } }```
Quote:

26620=Stalbridge Colonist
26500=Dawn Run
25190=Senor El Betrutti
25130=Poliantas
24860=Afleet Alex
23660=Barton Bank
23120=The Grey Monk
22920=Alydar
22760=Voy Por Ustedes
22620=Master Oats
22460=Norton's Coin
20880=Rough Quest
20610=Young Kenny
20290=Assault
20190=Pridwell
19360=Lord Gyllene
17820=General Wolfe
17730=Affirmed
15320=Cab On Target
15270=Uncle Ernie

• 05-28-2013, 09:03 PM
jim829
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
I am not certain what the problem is but I assume want to change the natural ordering of the map to descending order. To do that you can provide your own Comparator. Check out the Comparator API.

Typical usage would be:

Code:

```// create anonymous class Comparator<Integer> comp = new Comparator<Integer>() {         public int compare(Integer a, Integer b) {           return b.compareTo(a);         } }; SortedMap<Integer, String> bets = new TreeMap<comp>();```
Regards,
Jim
• 05-29-2013, 01:02 PM
chiba
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
I can't really understand how to store and sort the data

Affirmed £17730
Afleet Alex £24860
Alydar £22920
Assault £20290
Barton Bank £23660
Bobbyjo £25190

If my data is like the above stored in SortedMap then I can only sort by the key eg 'Barton Bank', but I want to sort by the amount.
Quote:

SortedMap map = new TreeMap();
I can easily create a new SortedMap and use the Integer amount as the key, but it seems like a waste of memory.
• 05-29-2013, 03:46 PM
jim829
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
Well, there is nothing wrong with doing it that way. It is probably the most direct way in fact. Otherwise you could simply use a List with entries of the form

Code:

```class MyEntry {     String key;     Integer value;     MyEntry(String key, Integer, Value) {         this.key = key;         this.value = value;     } }```
Then just sort the list using the value part of the entry. By doing it this way, you lose the ability to access an entry based on the horse name.

Regards,
Jim
• 05-29-2013, 04:01 PM
chiba
Re: Arrays vs HashMaps vs TreeSets - best method for sorting ability
I used an object to solve it

Code:

```import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Scanner; class Horse implements Comparator<Horse>, Comparable<Horse>{   private String name;   private int amount;   private int bets;   Horse(){   }   Horse(String n, int a, int b){       name = n;       amount = a;       bets=b;   }   public String getHorseName(){       return name;   }   public int getHorseAmount(){       return amount;   }   public int getBets(){               return bets;   }   public void setHorseAmount(int a){               amount=a;   }   public void increment(){               bets++;   }   // Overriding the compareTo method   public int compareTo(Horse d){       return (this.name).compareTo(d.name);   }   // Overriding the compare method to sort the age   public int compare(Horse h, Horse h1){       //return h.amount - h1.amount;           return h1.bets - h.bets;   } } public class race {         public static void main(String args[]){               // Takes a list of Horse objects               List<Horse> list = new ArrayList<Horse>();               File file = new File("horses.tsv");                     boolean hexists;               int amount;               int temp_a;               String temp_s;               String horse;               String[] parts;                                       try                         {                                 Scanner scanner = new Scanner(file);                                 String line = scanner.nextLine();                                                                 while (line != null)                                 {                                         hexists =false;                                                                 parts = line.split("\t");                                 horse=parts[0];                                 amount=Integer.parseInt(parts[1]);                                                                     for(Horse a: list)                                     {                                             temp_s=a.getHorseName();                                               if(temp_s.equals(horse))                                               {                                                       hexists =true;                                                       temp_a=a.getHorseAmount();                                                       amount=amount+temp_a;                                                       a.setHorseAmount(amount);                                                       a.increment();                                                       break;                                               }                                     }                                                                                             if (!hexists)                                 {                                         list.add(new Horse(horse,amount,1));                                 }                                 line = scanner.nextLine();                                 }                                                         }                         catch (Exception e)                         {                             //System.out.println(e);                                                     }                             Collections.sort(list, new Horse());               System.out.println();                             for(Horse a: list)                 System.out.println(a.getHorseName() +",  £ "+                         a.getHorseAmount() + ", number of bets " + a.getBets());           } }```
Code:

``` Senor El Betrutti,  £ 25190, number of bets 53 Stalbridge Colonist,  £ 26620, number of bets 51 Afleet Alex,  £ 24870, number of bets 49 Assault,  £ 20290, number of bets 48 Alydar,  £ 22920, number of bets 48 Poliantas,  £ 25130, number of bets 48 Rough Quest,  £ 20880, number of bets 47 Barton Bank,  £ 23660, number of bets 47 Dawn Run,  £ 26500, number of bets 46 Bobbyjo,  £ 25190, number of bets 45 Pridwell,  £ 20190, number of bets 44 Voy Por Ustedes,  £ 22760, number of bets 43 Master Oats,  £ 22620, number of bets 42 Lord Gyllene,  £ 19360, number of bets 42 General Wolfe,  £ 17820, number of bets 41 The Grey Monk,  £ 23120, number of bets 41 Norton's Coin,  £ 22460, number of bets 41 Young Kenny,  £ 20610, number of bets 39 Wayward Lad,  £ 23290, number of bets 38 Lady Rebecca,  £ 18780, number of bets 38 Uncle Ernie,  £ 15270, number of bets 38 Affirmed,  £ 17730, number of bets 37 Cab On Target,  £ 15320, number of bets 34```