This is my demo.jsp page,
<%
String key = request.getParameter("key");
String[] keyArray = key.split(",");
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < keyArray.length; i++) {
map.put(+i + "", keyArray[i]);
}
CommonFunction cf = new CommonFunction();
cf.sortByValues(map);
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while (iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry) iterator2.next();
out.println(me2.getValue());
}
%>
Here keyArray contains "similar
,rahul
,hashmap
,linkedlist
,demo
,ab
"; for this i need to sort according to length or according to string starts with character.
and common functions is
public class CommonFunction {
public HashMap sortByValues(HashMap map) {
List list = new LinkedList(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
}
});
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
}
this code working(sorting) fine when i gave eg:b,c,a,d
showing output a b c d
but when i gave String as "similar
,rahul
,hashmap
,linkedlist
,demo
,ab" showing output as
linkedlist hashmap rahul similar ab demo` ,so can anybody help me where to change the code.