Advertisement
jasonpogi1669

Sorting with Lambda Function using Java

Apr 5th, 2022 (edited)
1,416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Student {
  5.    
  6.     String name;
  7.     int age, id;
  8.    
  9.     Student(String name, int age, int id) {
  10.         this.name = name;
  11.         this.age = age;
  12.         this.id = id;
  13.     }
  14.    
  15.     public String getName() {
  16.         return this.name;
  17.     }
  18.    
  19.     public int getAge() {
  20.         return this.age;
  21.     }
  22.    
  23.     public int getId() {
  24.         return this.id;
  25.     }
  26.    
  27.     @Override
  28.     public String toString() {
  29.         return ("Name: " + this.getName() +
  30.                 ", Age: " + this.getAge() +
  31.                 ", Id: " + this.getId());
  32.     }
  33. }
  34.  
  35. public class Main {
  36.    
  37.     static void printList(ArrayList<Student> studentList) {
  38.         for(Student s : studentList) {
  39.             System.out.println(s);
  40.         }
  41.     }
  42.    
  43.     public static void main(String[] args) {
  44.    
  45.         ArrayList<Student> studentList = new ArrayList<Student>();
  46.         studentList.add(new Student("Jon", 22, 1001));
  47.         studentList.add(new Student("Steve", 19, 1003));
  48.         studentList.add(new Student("Kevin", 23, 1005));
  49.         studentList.add(new Student("Ron", 20, 1010));
  50.         studentList.add(new Student("Lucy", 18, 1111));
  51.        
  52.         // original sequence
  53.         System.out.println("Before sorting the student data:");
  54.         printList(studentList);
  55.        
  56.         // sorting by age
  57.         System.out.println("\nSorting by Age:");
  58.         studentList.sort((Student s1, Student s2) -> s1.getAge() - s2.getAge());
  59.         printList(studentList);
  60.        
  61.         // sorting by name
  62.         System.out.println("\nSorting by name:");
  63.         studentList.sort((Student s1, Student s2) -> s1.getName().compareTo(s2.getName()));
  64.         printList(studentList);
  65.        
  66.         // sorting by id
  67.         System.out.println("\nSorting by id:");
  68.         studentList.sort((Student s1, Student s2) -> s1.getId() - s2.getId());
  69.         printList(studentList);
  70.     }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement