desislava_topuzakova

7. Order by Age

Oct 30th, 2021
1,356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. package OrdeByAge_07;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Comparator;
  5. import java.util.List;
  6. import java.util.Scanner;
  7.  
  8. public class Main {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.         String personalInformation = scanner.nextLine();
  12.         List<Person> listOfPeople = new ArrayList<>();
  13.         while(!personalInformation.equals("End")) {
  14.             //"George 123456 20".split(" ") -> ["George", "123456", "20"]
  15.             String name = personalInformation.split(" ")[0];
  16.             String id = personalInformation.split(" ")[1];
  17.             int age = Integer.parseInt(personalInformation.split(" ")[2]);
  18.  
  19.             Person person = new Person(name, id, age);
  20.             listOfPeople.add(person);
  21.  
  22.             personalInformation = scanner.nextLine();
  23.         }
  24.  
  25.         //списък с хората
  26.         //сортиране по възраст в нарастващ ред (ascending order)
  27.         listOfPeople.sort(Comparator.comparing(Person::getAge));
  28.  
  29.         for (Person person : listOfPeople) {
  30.             System.out.println(person.toString());
  31.         }
  32.  
  33.     }
  34. }
  35.  
  36.  
  37.  
  38.  
  39. package OrdeByAge_07;
  40.  
  41. public class Person {
  42.     //полета -> характеристики
  43.     private String name;
  44.     private String id;
  45.     private int age;
  46.  
  47.     //конструктор
  48.     public Person(String name, String id, int age) {
  49.         this.name = name;
  50.         this.id = id;
  51.         this.age = age;
  52.     }
  53.  
  54.     //getter -> age
  55.     public int getAge() {
  56.         return this.age;
  57.     }
  58.  
  59.     @Override
  60.     public String toString() {
  61.         //"{name} with ID: {id} is {age} years old."
  62.         return String.format("%s with ID: %s is %d years old.", this.name, this.id, this.age);
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment