Jump to content

More specific sorting question


spoonraker

Recommended Posts

What I have to start with is a list of IDs and Strings, we'll say name for example. The IDs are unique to the name, and not in any particular orderex.ID Name--------------123 Bob3902 George392 Paul99833 AlexWhat I need to do is sort the list by Name, and then generate a list of IDs from this sorted list.In the example above, the final list I need would be : 99833, 123, 3902, 392Also, the final list needs to be indexed numerically so I can loop through it, so something like an array where array[0] = 99833, array[1] = 123, etc.It doesn't have to be a basic array, you can use any type of list, as long as it's loopable. So even something like an ArrayList would work. (int)arrayList.get(Integer.toString(0)) should be 99833, etc.Any ideas?

Link to comment
Share on other sites

Well nevermind, I got it figured out.In case you're wondering I used a Hashtable to store the original ID/Name combo. I actually used the Name as the key and the ID as the value. Then I created a Vector of the keySet from the Hashtable using the .keySet() method, which I sorted using Collections.sort(). Then I created an Interator from the vector, and used that to loop through the original hashtable, using the values of my sorted vector as keys for the hashtable.

<%@ page import="java.util.*" %><%String[] array1 = {"Bob","Alex","Chris","Dale","Elizabeth"};String[] array2 = {"243","3342","38294","8429","482929399"};	Hashtable h = new Hashtable();		for(int x=0;x<array1.length;x++){		h.put(array1[x].toLowerCase(), array2[x]);	}	// unsorted keys output	out.println("Unsorted <br><br>");	Iterator it = h.keySet().iterator();	while (it.hasNext()) {	   String element =  (String)it.next();	   out.println(element + " " + (String)h.get(element) + "<br>");	}	out.println("<br>Sorted by name <br><br>");	// sorted keys output  thanks to T. GUIRADO for the tip!	Vector v = new Vector(h.keySet());	Collections.sort(v);	it = v.iterator();	while (it.hasNext()) {	   String element =  (String)it.next();	   out.println( element + " " + (String)h.get(element) + "<br>");	}		out.println("<br>ID sorted by name<br><br>");		Iterator test = v.iterator();	while(test.hasNext()){		String element = (String)test.next();		out.println((String)h.get(element) + "<br>");	}%>

Unsortedelizabeth 482929399bob 243alex 3342chris 38294dale 8429Sorted by namealex 3342bob 243chris 38294dale 8429elizabeth 482929399ID sorted by name3342243382948429482929399

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...