Sort ArrayList of HashMaps
Hello all
I have Arraylist that contains HashMaps
how can I sort the ArrayList by some value of HashMaps?
e.g. I have following HashMaps that are put inside a list and need to sort them by there value
ArrayList<HashMap> al = new ArrayList<HashMap>();
HashMap map1 = new HashMap();
map1.add( new Integer( 2 ), "two" );
map1.add( new Integer( 4 ), "four" );
HashMap map2 = new HashMap();
map2.add( new Integer( 22 ), "two2" );
map2.add( new Integer( 42 ), "four2" );
HashMap map3 = new HashMap();
map3.add( new Integer( 23 ), "two" );
map3.add( new Integer( 43 ), "four" );
al.add(map1);
al.add(map2);
al.add(map3);Thanks
Create a Comparator<HashMap> and pass that to Collections.sort. Write the comparator to use whatever rules you need to determine whether a map is "less than" another.
http://java.sun.com/javase/6/docs/api/java/util/Comparator.html
http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)
http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html
Similar Messages
-
Hi,
I have Arraylist of Hashmaps, and each hashmap has 10 Key-value pairs.
How to sort this Arraylist of Hashmaps?
Any suggestions/ Example?
ThanksWhat is your criteria for one HashMap coming 'before' or 'after' another? You can create a Comparator which contains those rules and pass it to the sort routine.
Edit: Sorry, ended up adding nothing to the original answer. If you google "Comparator examples" you'll find some good stuff.
Edited by: JEisen on Jul 21, 2009 3:49 PM -
Question | Using JSTL to Display elements of an ArrayList of HashMaps
Hi All,
I would like some advice on the following code snippet which is a representation of my real code. Please see below for the code snippet and the specific questions I have.
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%
// This Object is an ArrayList of HashMaps
MyClassDataBean myDb = (MyClassDataBean)session.getAttribute("testDataBean");
// Adding myDb to the pageContext so that EL can be used to render components in this Object
pageContext.setAttribute("myDb",myDb);
pageContext.setAttribute("column1",MyConstants.COLUMN1);
pageContext.setAttribute("column2",MyConstants.COLUMN2);
%>
<html>
<head></head>
<body>
<c:choose>
<c:when test="${myDb != null}" >
<c:forEach var="hashMapAsRow" items="${myDb}" varStatus="lineInfo">
<tr>
<td><c:out value="${hashMapAsRow[column1]}" /></td>
<td><c:out value="${hashMapAsRow[column2]}" /></td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr><td colspan="100%">No Data Exists</td></tr>
</c:otherwise>
</c:choose>
</body>
</html>Question: Is there an alternative to accessing elements using the core tag library in this Object without using pageContext.setAttribute() ? If not, would the c_rt library be better to use in this scenario? If so, could someone give me an example of the right way to use it based on the above example?
Thanks,
Joe<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:set var="myDb" value="${sessionScope.testDataBean}" />
<html>
<head></head>
<body>
<c:choose>
<c:when test="${myDb != null}" >
<c:forEach var="hashMapAsRow" items="${myDb}" varStatus="lineInfo">
<tr>
<td><c:out value="${hashMapAsRow['column1']}" /></td>
<td><c:out value="${hashMapAsRow['column2']}" /></td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr><td colspan="100%">No Data Exists</td></tr>
</c:otherwise>
</c:choose>
</body>
</html> or the one below
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
<head></head>
<body>
<c:choose>
<c:when test="${sessionScope.testDataBean != null}" >
<c:forEach var="hashMapAsRow" items="${sessionScope.testDataBean}" varStatus="lineInfo">
<tr>
<td><c:out value="${hashMapAsRow['column1']}" /></td>
<td><c:out value="${hashMapAsRow['column2']}" /></td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr><td colspan="100%">No Data Exists</td></tr>
</c:otherwise>
</c:choose>
</body>
</html> is this the one which you are looking for ??
REGARDS,
RaHuL -
Sorting ArrayList multiple times on Multiple Criteria
I have an arraylist that is sorted with Collection.sort() calling the ComparTo() included below. CompareTo sorts the file on totalLaps, totalSeconds, and etc.. The question is how do I change the sort criteria later in my process so that the arraylist is sorted on sequence number (the first field and a long number)? The only way I can currently think of doing it is to copy the array and create a separate class file like RaceDetail2 that implements a different CompareTo. To me that seems ridiculous!
I've self tought myself Java using the online tutorials and a few books so sometimes I find I have some basic gaps in knowledge about the language. What am I missing? Seems like it should be simple.
private ArrayList detailsArrayList = new ArrayList( );
// Sort arraylist using compareTo method in RaceDetail file
Collections.sort(detailsArrayList);
public class RaceDetail implements Comparable, Cloneable {
public RaceDetail( long seqNum, String boatNumText, int lapNum, String penalty, String question, long seconds, int totalLaps, long totalSecs, long lastSeqNum, long avg, long interval )
public int compareTo( Object o )
RaceDetail rd = (RaceDetail) o;
int lastCmp = (totalLaps < rd.totalLaps ? -1: (totalLaps == rd.totalLaps ? 0: 1));
int lastCmpA = boatNumText.compareTo(rd.boatNumText);
int lastCmpB = (lapNum < rd.lapNum ? -1: (lapNum == rd.lapNum ? 0 : 1 ));
int lastCmpC = (totalSecs < rd.totalSecs ? -1 : (totalSecs == rd.totalSecs ? 0 : 1 ));
int lastCmpD = (seqNum < rd.seqNum ? -1 : (seqNum == rd.seqNum ? 0 : 1 ));
int lastCmpE = (seconds < rd.seconds ? -1 : (seconds == rd.seconds ? 0 : 1 ));
int lastCmpF = (lastSeqNum < rd.lastSeqNum ? -1 : (lastSeqNum == rd.lastSeqNum ? 0 : 1 ));
// TotalLaps - Descending, TotalSeconds - ascending, lastSeqNum - ascending
// Boat - Ascending, Second - ascending, seqNum - ascending
return (lastCmp !=0 ? -lastCmp :
(lastCmpC !=0 ? lastCmpC :
(lastCmpF !=0 ? lastCmpF :
(lastCmpA !=0 ? lastCmpA :
(lastCmpE !=0 ? lastCmpE :
lastCmpD)))));
}Thanks talden, adding the comparator below in my main program flow worked and now the arraylist sorts correctly. A couple of additional questions. I tried to place this in my RaceDetail class file and received a compile error so placed it in the main program flow and it worked fine. For organization, I would like to place all my sort routines together. Is there some trick to calling this method if I place it in my RaceDetail? Am I even allowed to do that?
dhall - just to give you a laugh, this arraylist populates a JTable, uses a TableModel, and the TableSorter from the tutorial. Sorting works great in the JTable. Problem is I have to sort the arraylist a couple of times to calculate some of the fields such as lap times and total laps. I went through the TableSorter 5 or 6 times and never could figure out how to adapt it for what I wanted to do. So here I am using an example in my program and can't interpret it.
Collections.sort( detailsArrayListLeft, SORT_BY_SEQUENCE );
static final Comparator SORT_BY_SEQUENCE = new Comparator() {
public int compare ( Object o1, Object o2 )
RaceDetail rd1 = (RaceDetail) o1;
RaceDetail rd2 = (RaceDetail) o2;
return (rd1.seqNum() < rd2.seqNum() ? -1 : (rd1.seqNum() == rd2.seqNum() ? 0 : 1 )); -
Hi to all,
I have to sort ArrayList elements in alphabetical order.When i tried to do with the following code iam getting "java.lang.ClassCastException:".
List lStyleArray = new ArrayList();
lStyleArray =(ArrayList)xxx.getxxx();
Collections.sort(lStyleArray );
Could anybody help to overcome this problem.Thanks in advancePresumably, "xxx.getxxx()" is returning something that is not an ArrayList.
So you have to fix that, or change what you're trying to do. Maybe it's a List other than an ArrayList. You don't need to cast it to be an ArrayList specifically, probably.
Also are you aware that on the first line, you're creating an ArrayList and then immediately throwing it away? -
Sort ArrayList of objects by id
I have ArrayList of containing 'MonthlySale' objects, below is my class.
import java.io.Serializable;
import java.util.ArrayList;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="Month")
public class MonthlySale extends AuraDB implements Serializable, Comparable {
private String quantity;
private String value;
private String avUnit;
private int saleNumber;
private int id;
private String month;
private String saleYear;
private String description;
private int reportNumber;
public MonthlySale() {
public MonthlySale(int saleNumber, String saleYear) {
this.saleNumber = saleNumber;
this.saleYear = saleYear;
public MonthlySale(int saleNumber, String saleYear, int reportNumber) {
this.saleNumber = saleNumber;
this.saleYear = saleYear;
this.reportNumber = reportNumber;
@Column(name="AV_UNIT")
public String getAvUnit() {
return avUnit;
public void setAvUnit(String avUnit) {
this.avUnit = avUnit;
@Column(name="MONTH")
public String getMonth() {
return month;
public void setMonth(String month) {
this.month = month;
@Column(name="QUANTITY")
public String getQuantity() {
return quantity;
public void setQuantity(String quantity) {
this.quantity = quantity;
@Column(name="SALES_NO")
public int getSaleNumber() {
return saleNumber;
public void setSaleNumber(int saleNumber) {
this.saleNumber = saleNumber;
@Column(name="SALES_YEAR")
public String getSaleYear() {
return saleYear;
public void setSaleYear(String saleYear) {
this.saleYear = saleYear;
@Column(name="VALUE")
public String getValue() {
return value;
public void setValue(String value) {
this.value = value;
@Id
@GenericGenerator(name="generator", strategy="increment")
@GeneratedValue(generator="generator")
@Column(name="ID")
public int getId() {
return id;
public void setId(int id) {
this.id = id;
@Column(name="DESCRIPTION")
public String getDescription() {
return description;
public void setDescription(String description) {
this.description = description;
@Column(name="REPORT_ID")
public int getReportNumber() {
return reportNumber;
public void setReportNumber(int reportNumber) {
this.reportNumber = reportNumber;
public void selectMonthList() {
hibSelectAll(this, "SELECT DISTINCT month FROM MonthlySale WHERE sales_year='" + saleYear + "' AND " +
" sales_no = '" + saleNumber + "'");
}I want my arraylist to be ordered by id. I used collection.sort(), but i cannot sort by id.
I get objects arrayList like this way
monthlySale = new MonthlySale(Integer.parseInt(sales_no), sales_year, 0);
monthlySale.selectMonthList();Any help appreciated.
regards,
Dil.Of course yes i did, like this.
public int compareTo(Object o) {
if(this.id == ((MonthlySale)o).getId()){
return 0;
}else if(this.id > ((MonthlySale)o).getId()){
return 1;
}else{
return -1;
}I implement 'MonthlySale class' form Comparable interface and override above method but it doesn't work. -
Hi
I have class like below , i store them in a ArrayList, is it possible to sort this ArrayList by name or by date.
The class is as below
public class MyInfo
private String name;
private Date date;
//have getters and setters for name and date
ArrayList data = new ArrayList();
data.add(instance of MyInfo)
AshishComparable doesn't really apply here IMO, since he
uses different ordering criteria - name and date.Did you read the link? The tutorial contains useful information on the Comparator as well as the Comparable interface, which is why I posted it. I believe you're objecting only to the title of the article.
:o) -
I need to remove the string(s) with the least number of letters from an ArrayList.
How can I sort the ArrayList by the length of the strings contained in it?Why would you need to?
1.5 (you should be using an ArrayList<String>)
list.get(i).length();Earlier (without generics)
((String)list.get(i)).length();This is of course irrelevent to impelementing a
simple Comparator and passing it to Collections.Or
list.get(i).toString().length();
Or
new StringBuilder(list.get(i).toString().toCharArray()).toString(); -
Collecstions.sort(ArrayList) - Please Explain
Hello,
This is a rewrite of an earlier question. Hopefully, I better formed the question in this post.
Can anyone explain why the first code example requires that I write a compareTo() method (called by Collections.sort(bidList)) and a toString() method (called by System.out.println(bidList), while the second code example requires no such additional code in my program?
Thanks for all responses.
Karl
First Code Example (Requires comparTo() and toString() methods in the program.)
public static void main(String[] args) {
// fill a list with 5 bids
ArrayList bidList = new ArrayList();
for(int i=0; i<5; i++){
//generate random number 0-100 for a bid amount
bidList.add(new AuctionBid("Bidder" + i, (int)(Math.random()*100)));
//sort the bids in natural order and display them
Collections.sort(bidList); //Why does this call method compareTo()
System.out.println("Natural order sort by bid amount");
System.out.println(bidList); //Why does this call method toString()
}Second Code Example (Does not require compareTo() or toString() methods in the program.)
public static void main(String[] args) {
// fill a list with 5 bids
System.out.println("Printing bidList from Array: ");
String[] bidList = new String[5];
for(int i=0; i<5; i++){
if(i==0){bidList[i] = "Zoey";}
else if (i==1){bidList[i] = "Megan";}
else if (i==2){bidList[i] = "Larrry";}
else if (i==3){bidList[i] = "Brian";}
else if (i==4){bidList[i] = "Abigail";}
List list2 = Arrays.asList(bidList); // Does NOT requre a toString() method to be coded.
System.out.println("Printing Unsorted list2: ");
System.out.println(list2);
Collections.sort(list2); // Does NOT require a compareTo() method to be coded.
System.out.println("Printing Sorted list2: ");
System.out.println(list2);
}To answer your first question, Collections doesn't
know how to sort any ArrayList unless the objects
implement the Comparable interface and define the
compareTo method. The String class already defines
the compareTo method for you, and that's why your
second ArrayList doesn't require you to write one.
In your first list you're loading AuctionBid
references, and Collections can't sort that list
unless your AuctionBid class implements Comparable
and defines the compareTo method.
To answer your second question, System.out.println
calls toString on the object reference you pass to
it, unless the reference actually IS a String
reference. How else could it get a string
representation of an object without calling toString
on it?Thank you!
That makes sense.
Karl -
Sort ArrayList on multiple values
Hi all!
i'm trying to sort an ArrayList that contains a list of beans with a bunch of properties.
i think that the comparator should be written like this:
protected class CategoryComparator implements Comparator {
public int compare(Object o1, Object o2) {
Category cat1 = (Category)o1;
Category cat2 = (Category)o2;
return cat1.getCategoryName().compareTo(cat2.getCategoryName()) & cat1.getCategoryId().compareTo(cat2.getCategoryId());
}where Category is the bean, getCategoryName and getCategoryId return two strings. Is that right to get the list sorted on both the two fields?
Thanks!No, it's not. Assuming categoryName is of higher priority, you want int comp = cat1.getCategoryName().compareTo(cat2.getCategoryName());
if (comp != 0) return comp;
return cat1.getCategoryId().compareTo(cat2.getCategoryId()); -
hi,
some doubts on the syntax
rows.add(String.valueOf(destList));is this the correct syntax eventhough my "destList" is an integer?
Collections.sort(rows);i would like to sort my arrayList but it doesnt seem to work with this syntax.the values in my arraylist are in integer.
please help.thanksMaybe a little off topic, but this might be of interest to anyone that wants to sort a 2 dim object array (Object[][]).
As part of the formatteddataset open source API I have a utility class called ArraySQL. It allows you to issue a reduced sql syntax against an array (i.e. specify a column list, where and order by clauses). The basic idea is that because a 2 dim Array is conceptually similar to a db table you could be able to query it. I will be releasing on sourceforge in a couple weeks, but in the meantime if anyone is interested i can send it to them. Here are some examples
import com.fdsapi.arrays.ArraySQL;
Object[][] data{
{"jim","smith", new Integer(200)},
{"jeff","souza", new Integer(500)},
{"jim","anderson", new Integer(100)},
{"stan","jones",new Integer(2000)}};
ArraySQL asql=new ArraySQL("select * from array where col0 in ('jim', 'jeff') order by col0 asc, col1 desc")
Object[][] newData=asql.execute(data);
asql=new ("select * from array order by col2 desc");
newData=asql.execute(data);steve -
http://www.fdsapi.com - An easy, fast, extensible way of generating xml and html
http://www.jamonapi.com - An easy way to monitor application code.
Both tools are open source and available for download on the given sites. -
I am not sure if this can be done. I randomly add elements to ArrayList and arrange in increasing order, can this be done...
for example,
ArrayList<String> tempList = new ArrayList <String>();
tempList.set(o,"aaa");
tempList,set(3,"bbb");
tempList.set(1,"ddd");
tempList.set(2,"ccc");Then I would like to sort them so that I can print them in order, i.e. element at 0, then 1, then 2, then 3....
How can I do this?I am not sure if this can be done. I randomly add
elements to ArrayList and arrange in increasing
order, can this be done...
for example,
ArrayList<String> tempList = new ArrayList
<String>();
tempList.set(o,"aaa");
tempList,set(3,"bbb");
tempList.set(1,"ddd");
tempList.set(2,"ccc");Then I would like to sort them so that I can print
them in order, i.e. element at 0, then 1, then 2,
then 3....
How can I do this?Something says me that [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort(java.util.List)]Collections.sort(List list)★ can help you.
API Documentation is your friend
*** -
i have used jstl to iterate Arraylist to display car name,price and other details.
Can anyone help me in sorting out the table based on list box value selected.ie sort by name,sort by model,sort by price,,
please suggest me ,if it can be done using any taglib
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h1>Car List</h1>
<h1></h1>
<select>
<option>Sort by Name</option>
<option>Sort by Model</option>
<option>Sort by Price</option>
</select>
<table>
<c:forEach items="${carList}" var="car">
<tr>
${car.brand.name} ${car.model}: ${car.price}
</tr>
</c:forEach>
</table>
</body>
</html>
----------------------------------------------------------------------------------------------------------------user8619787 wrote:
i have used jstl to iterate Arraylist to display car name,price and other details.
Can anyone help me in sorting out the table based on list box value selected.ie sort by name,sort by model,sort by price,,
please suggest me ,if it can be done using any taglib
Nope, either have your Car class implement Comparable or else use a Comparator. You need to sort it before setting it to scope for use in the jsp
cheers,
ram. -
How can you sort an ArrayList in ascending order without using the following line of code?
Collections.sort(myArrayList);I've come up with a bit of code so far, but I have an error message that says "incompatible types" for the two lines that define variables first and second. The code is supposed to be able to sort the ArrayList called "list" in ascending order, and save it into an ArrayList called "list2"... except I can't use that wonderful line of code I mentioned earlier that makes life so much darned easier. The code I'm posting is just the horrible code I have so far for the method that should sort it... all ArrayLists, etc. have been defined and all that good stuff. Any help would be greatly appreciated.
public static void sorter()
int count=1;
list2.add(list.get(0));
for(int i=0; i<list.size(); i++)
for(int f=0; f<list2.size(); f++)
int first=list.get(count);
int second=list2.get(f);
if(first<second)
list2.add(0,list.get(count));
break;
}Assuming the array holds Objects, you can't just assign them to an int. Try: // with autoboxing
// int first=(Integer)list.get(count);
// without
int first=((Integer)list.get(count)).intValue();[Edit]Indeed with autoboxingfor(Integer i=0; // etc... -
I have a problem while sort the List<Map> .
Please tell me how do i sort this type of data by using predefined sort procedured i.e sotedSet, sortedMap.
Thanks in advance............Collections.sort(theList, a Comparator)
Implement the Comparator the way you want.
Maybe you are looking for
-
Windows 8 activation is not working !!!
I just bought a brand new laptop Toshiba Stellite P75 2 months ago, and then there's no problem with it until yesterday. I started the windows and got an error message that i need to active the window. So when i when to Windows Activation and hit the
-
Insertion of relative path of dtd failing with XMLType
Hi We are using Oracle10g as the database and want to insert an xmltype data in the table. The problem is with the xml contains one relative path of the dtd file, which is existed in the local file system. Code snippet follows, <?xml version="1.0" en
-
Which Audio Setting for MPEG share for use on PC or burning to DVD???
I just "shared" a movie (a slide and video show with soundtrack edited on Premier Elements 8) to "Use for playback on this PC or burning to DVD" (created an MPEG). The audio export didn't work though. I used the NTSC DVD Standard preset that give
-
Openbox - switch desktop like in Xfce [SOLVED]
Hey all I've been using Xfce for a while now and I'm trying out Openbox, everything is great exept one feature that I miss. In Xfce I can move the mouse outside the screen to switch virtual desktops, which I've really gotten used to do, but I haven't
-
Can I download a copy of snow lepord, or do I have to purchase the cd, would much rather just download and upgrade