Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an ArrayList based on an object field [duplicate]

Tags:

java

Possible Duplicate:
Sorting an ArrayList of Contacts

I am storing DataNode objects in an ArrayList. The DataNode class has an integer field called degree. I want to retrieve DataNode objects from nodeList in the increasing order of degree. How can I do it.

List<DataNode> nodeList = new ArrayList<DataNode>(); 
like image 224
softwarematter Avatar asked Nov 01 '10 03:11

softwarematter


People also ask

Can an ArrayList can hold duplicate objects?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

How to remove duplicate from List using Java 8?

Remove duplicates in arraylist – Java 8. To remove the duplicates from the arraylist, we can use the java 8 stream api as well. Use steam's distinct() method which returns a stream consisting of the distinct elements comparing by object's equals() method. Collect all district elements as List using Collectors.


2 Answers

Use a custom comparator:

Collections.sort(nodeList, new Comparator<DataNode>(){      public int compare(DataNode o1, DataNode o2){          if(o1.degree == o2.degree)              return 0;          return o1.degree < o2.degree ? -1 : 1;      } }); 
like image 140
Mark Elliot Avatar answered Oct 03 '22 08:10

Mark Elliot


Modify the DataNode class so that it implements Comparable interface.

public int compareTo(DataNode o) {      return(degree - o.degree); } 

then just use

Collections.sort(nodeList); 
like image 22
blitzkriegz Avatar answered Oct 03 '22 08:10

blitzkriegz