/home/wpollock1/public_html/AJava/CollectionSortingDemo.java
// Testing new Java SE 8 features on collections.
// Written 8/2014 by Wayne Pollock, Tampa Florida USA
// From a 8/10/14 post on comp.lang.java.programmer by Sebastian,
// "Re: Lambda Expressions - Java 8 Feature", pointing to a blog post at:
// http://www.groupkt.com/post/088a8dea/lambda-expressions---java-8-feature.htm
import java.util.*;
import static java.util.Comparator.comparing;
public class CollectionSortingDemo {
public static void main ( String [] args ) {
List<Student> students = new ArrayList<>();
students.add( new Student( 1, "Jane", 18) );
students.add( new Student( 4, "John", 19) );
students.add( new Student( 3, "Kim", 18) );
students.add( new Student( 2, "Matt", 20) );
System.out.println( "Students before sorting:\n" + students );
students.sort( comparing(Student::getstudentID) );
// The method comparing() is a new static method in interface Comparator.
// The method sort() is a new default method in the List interface.
// Student::getstudentID is a method reference, it provides convenient
// shorthand for the corresponding lambda s -> s.getstudentID()
System.out.println( "\nStudents after sorting:\n" + students );
}
}
class Student {
private Integer studentID;
private String name;
private Integer age;
/**
* @param studentID
* @param name
* @param age
*/
public Student(Integer studentID, String name, Integer age) {
super();
this.studentID = studentID;
this.name = name;
this.age = age;
}
/**
* @return the studentID
*/
public Integer getstudentID() {
return studentID;
}
/**
* @param studentID the studentID to set
*/
public void setstudentID(Integer studentID) {
this.studentID = studentID;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public Integer getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return new StringBuilder()
.append("{studentID:").append(studentID)
.append(",name:").append(name)
.append(",age:").append(age)
.append("}\n")
.toString();
}
}