Jump to content

More specific sorting question

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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...