April 5th, 2023
Collection sort

Sort collection using stream and Lambda functions.

				
					import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Sorter1 {
	public static void main(String[] args) {
		List<Student> students = new ArrayList<>();
		students.add(new Student("A", 10));
		students.add(new Student("B", 12));
		students.add(new Student("C", 8));
		students.add(new Student("D", 9));
		students.add(new Student("E", 11));
		students.add(new Student("F", 14));
		
		System.out.println("=== Before Sort ============");
		students.forEach(i -> System.out.println(i.toString()));
		
		List<Student> list1 = students.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
				// OR
		List<Student> list1 = students.stream().sorted((a,b) -> a.getAge().compareTo(b.getAge())).collect(Collectors.toList());
		
		System.out.println("\n=== After Sort ============");
		list1.forEach(i -> System.out.println(i.toString()));
	}
}
				
			

Sort collection without stream.

				
					import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Sorter1 {
	public static void main(String[] args) {
		List<Student> students = new ArrayList<>();
		students.add(new Student("A", 10));
		students.add(new Student("B", 12));
		students.add(new Student("C", 8));
		students.add(new Student("D", 9));
		students.add(new Student("E", 11));
		students.add(new Student("F", 14));
		
		System.out.println("=== Before Sort ============");
		students.forEach(i -> System.out.println(i.toString()));
		
		students.sort(Comparator.comparing(Student::getAge));
		// OR
		students.sort((a,b)->a.getAge().compareTo(b.getAge()));
		
		System.out.println("\n=== After Sort ============");
		students.forEach(i -> System.out.println(i.toString()));
	}
}
				
			
				
					class Student{
	private String name;
	private Integer age;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String toString() {
		return this.name+" : "+ this.age;
	}
	public String getName() {
		return name;
	}
	public Integer getAge() {
		return age;
	}
}

				
			
				
					=== Before Sort ============
A : 10
B : 12
C : 8
D : 9
E : 11
F : 14

=== After Sort ============
C : 8
D : 9
A : 10
E : 11
B : 12
F : 14
				
			

Leave a Reply

Your email address will not be published. Required fields are marked *