| Author |
Sort and create new Objects before using TreeMap
|
Lucian Botezatul
Greenhorn
Joined: Jan 08, 2011
Posts: 20
|
|
have: List with 15 Objects (dummy)
The int value, random updated each ten steps (int)Math.round( Math.random() * 9 ).
Objects are sorted with TreeMap:
If i have some Objects like this: 20 Max, 18 Jane, 20 Mike, 22 John,
With my actual code i get the Result:
18 Jane
20 Mike
22 John
I would like something like this:
18 Jane
20 Max, Mike
22 John
My Idea: Put the Strings of the objects with the same int in one String together:
20 Max, 18 Jane, 20 Mike, 22 John, -> persort
20 Max compare 18 Jane -> no int mach
20 Max comparte 20 Mike-> match -> new Object 20 Max, Mike
....
result 20 Max, Mike; 18 Jane; 22 John -> run TreeMap over them and
18 Jane
20 Max, Mike
22 John
Any suggestions how i can make this pre sort, put the strings from the objects with the same (int) key on one new string of a new object?
|
 |
Luigi Plinge
Ranch Hand
Joined: Jan 06, 2011
Posts: 441
|
|
|
When you put a value into a map, it will return the previous value, or null if there was no previous entry. So do something like
|
 |
Lucian Botezatul
Greenhorn
Joined: Jan 08, 2011
Posts: 20
|
|
THANK YOU LUIGI !!! it works, very nice idea !!
Final working version:
SortedMap<Integer,String>Sortierte_liste2 = new TreeMap<Integer,String>(Collections.reverseOrder());
Teilnehmer Ben1 = new Teilnehmer();
Ben1.T_name = "Bernd";
Ben1.richtigeAntworten = n1;
String prev = Sortierte_liste2.put(Ben1.richtigeAntworten, Ben1.T_name);
if(prev != null){
Sortierte_liste2.put(Ben1.richtigeAntworten, prev + ", " + Ben1.T_name);
}
...........
Teilnehmer Ben10 = new Teilnehmer();
Ben10.T_name = "Noemi";
Ben10.richtigeAntworten = n10;
String prev10 = Sortierte_liste2.put(Ben10.richtigeAntworten, Ben10.T_name);
if(prev10 != null){
Sortierte_liste2.put(Ben10.richtigeAntworten, prev10 + ", " + Ben10.T_name);
}
Teilnehmer Anwender = new Teilnehmer();
Anwender.T_name = "----> " + nam + " <----";
Anwender.richtigeAntworten = antwortenAnwender;
Sortierte_liste2.put(Anwender.richtigeAntworten, Anwender.T_name);
ArrayList<String> namen;
namen = new ArrayList<String>();
JOptionPane myStatisticWindow = new JOptionPane();
JTextArea MyList = new JTextArea("Richtig beantwortete Fragen \n\n"); // inhalt in den Rahmen
MyList.setEditable(false);
MyList.setOpaque(false);
MyList.setFont(new Font("Arial", Font.PLAIN, 20));
for (Iterator it = Sortierte_liste2.entrySet().iterator(); it.hasNext(); )
{ // inner loop
Map.Entry entry = (Map.Entry) it.next();
MyList.append(entry.getKey().toString());
MyList.append(" " + "Fragen: ");
MyList.append(entry.getValue().toString());
MyList.append("\n");
}
myStatisticWindow.showMessageDialog(null, MyList, "Teilnehmer Liste", JOptionPane.DEFAULT_OPTION); //
result = namen.toArray();
return result;
}
|
 |
 |
|
|
subject: Sort and create new Objects before using TreeMap
|
|
|