CollectionSortingDemo.java

Download CollectionSortingDemo.java

 1: // Testing new Java SE 8 features on collections.
 2: // Written 8/2014 by Wayne Pollock, Tampa Florida USA
 3: // From a 8/10/14 post on comp.lang.java.programmer by Sebastian,
 4: // "Re: Lambda Expressions - Java 8 Feature", pointing to a blog post at:
 5: // http://www.groupkt.com/post/088a8dea/lambda-expressions---java-8-feature.htm
 6: 
 7: import java.util.*;
 8: import static java.util.Comparator.comparing;
 9: 
10: public class CollectionSortingDemo {
11:    public static void main ( String [] args ) {
12:       List<Student> students = new ArrayList<>();
13:          students.add( new Student( 1, "Jane", 18) );
14:          students.add( new Student( 4, "John", 19) );
15:          students.add( new Student( 3, "Kim", 18) );
16:          students.add( new Student( 2, "Matt", 20) );
17: 
18:       System.out.println( "Students before sorting:\n" + students );
19:       students.sort( comparing(Student::getstudentID) );
20:       // The method comparing() is a new static method in interface Comparator.
21:       // The method sort() is a new default method in the List interface.
22:       // Student::getstudentID is a method reference, it provides convenient
23:       // shorthand for the corresponding lambda s -> s.getstudentID()
24: 
25:       System.out.println( "\nStudents after sorting:\n" + students );
26:    }
27: }
28: 
29: class Student {
30: 	private Integer studentID;
31: 	private String name;
32: 	private Integer age;
33: 
34: 	/**
35: 	 * @param studentID
36: 	 * @param name
37: 	 * @param age
38: 	 */
39: 	public Student(Integer studentID, String name, Integer age) {
40: 		super();
41: 		this.studentID = studentID;
42: 		this.name = name;
43: 		this.age = age;
44: 	}
45: 	/**
46: 	 * @return the studentID
47: 	 */
48: 	public Integer getstudentID() {
49: 		return studentID;
50: 	}
51: 	/**
52: 	 * @param studentID the studentID to set
53: 	 */
54: 	public void setstudentID(Integer studentID) {
55: 		this.studentID = studentID;
56: 	}
57: 	/**
58: 	 * @return the name
59: 	 */
60: 	public String getName() {
61: 		return name;
62: 	}
63: 	/**
64: 	 * @param name the name to set
65: 	 */
66: 	public void setName(String name) {
67: 		this.name = name;
68: 	}
69: 	/**
70: 	 * @return the age
71: 	 */
72: 	public Integer getAge() {
73: 		return age;
74: 	}
75: 	/**
76: 	 * @param age the age to set
77: 	 */
78: 	public void setAge(Integer age) {
79: 		this.age = age;
80: 	}
81: 
82: 	@Override
83: 	public String toString() {
84: 		return new StringBuilder()
85: 		.append("{studentID:").append(studentID)
86: 		.append(",name:").append(name)
87: 		.append(",age:").append(age)
88: 		.append("}\n")
89: 		.toString();
90: 	}
91: }