Sorting Using Comparator
package java8examples;
import java.math.BigDecimal;
//import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestSorting {
public static void main(String[] args) {
List<Developer> listDevs = getDevelopers();
System.out.println("Before Sort");
for (Developer developer : listDevs) {
System.out.println("ID : "+developer.getId()+" DEV Name : "+developer.getName());
}
//sort by age
Collections.sort(listDevs, new Comparator<Developer>() {
@Override
public int compare(Developer o1, Developer o2) {
return o1.getId() - o2.getId();
}
});
System.out.println("After Sort");
for (Developer developer : listDevs) {
System.out.println("ID : "+developer.getId()+" DEV Name : "+developer.getName());
}
}
private static List<Developer> getDevelopers() {
List<Developer> result = new ArrayList<Developer>();
result.add(new Developer("mkyong", 33));
result.add(new Developer("alvin", 20));
result.add(new Developer("jason", 10));
result.add(new Developer("iris", 55));
return result;
}
}
===========
package java8examples;
import java.math.BigDecimal;
public class Developer {
String name;
int id;
String designation;
String project;
public Developer(String name, int id) {
super();
this.name = name;
this.id = id;
}
public Developer(String string, BigDecimal bigDecimal, int i) {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Developer other = (Developer) obj;
if (id != other.id)
return false;
return true;
}
}
Comments
Post a Comment