Hello,

I have a question about sorting.

How can I sort HashMap by element in the HashMap ?
That's meaning, if I have in the Sys class map such as:

protected Map <Constructors,RaceTeam>raceTeam=new HashMap<Constructors,RaceTeam>();

and in the RaceTeam class I have this variables:

protected Constructors name;
	protected int totalScore;
	protected URL website;
	protected double budget;
	protected Race lastRace;

and I want to sort the the eaceTeam map by the "totalScore" from the biggest to the smallest, How can I do this thing ?

I do the follwing:

TreeMap<Integer,RaceTeam> teams = new TreeMap<Constructors,RaceTeam> teams = new TreeMap<Constructors,RaceTeam>();		
		Iterator iter = teams.keySet().iterator();
	    Object obj;
	    
	    while (iter.hasNext()) {
		      obj = iter.next();
		      System.out.println(teams.get(obj).getName() + " " + teams.get(obj).getTotalScore());
		    }

The out put will be:
Brawn 390
Toyota 584
BMW_Sauber 470
Renault 782
Toro_Rosso 488
Force_India 0
Ferrari 1049

I want it to be:
Ferrari 1049
Renault 782
Toyota 584
Toro_Rosso 488
BMW_Sauber 470
Brawn 390
Force_India 0

TreeMaps are held sorted by key, so if you want to see the values sorted in some other order you need to get the values as a simple collection teams.values() and then use Collections.sort to sort it using a custom comparator that compares raceTeams by their names.

but I sholud not use collection.sort

I should do it without collection.sort

I do the following:

public void printRaceTeamsRankedReport(){
		TreeMap<Constructors,RaceTeam> teams = new TreeMap<Constructors,RaceTeam>();
		teams.putAll( raceTeam);
		TreeMap <Integer,Constructors> teamCo = new TreeMap <Integer,Constructors>();
		

		Object obj;
	    Iterator itera = teams.keySet().iterator();
	    while ((itera.hasNext())) {

	    	obj = itera.next();
	    	teamCo.put(teams.get(obj).getTotalScore(), teams.get(obj).getName());
		    }
	    
	    MyFileLogWriter.writeToFileInSeparateLine("\n====Race Teams Ranked Report====");
	    
	    Iterator it = teamCo.keySet().iterator();
//	    Object obj;
	    MyFileLogWriter.writeToFileInSeparateLine(teamCo.descendingMap());
	    MyFileLogWriter.writeToFileInSeparateLine("====End of Race Teams Ranked Report====\n");		
		
	}

The output is:
{1049=Ferrari, 782=Renault, 584=Toyota, 488=Toro_Rosso, 470=BMW_Sauber, 390=Brawn, 0=Force_India}


How can get it like this :

Ferrari 1049
Renault 782
Toyota 584
Toro_Rosso 488
BMW_Sauber 470
Brawn 390
Force_India 0

This question has already been answered. Start a new discussion instead.