deyanmalinov

1. Sort by Name and Age

Jun 9th, 2020
1,088
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package DPM;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Scanner;
  5. public class Main {
  6.     public static void main(String[] args) {
  7.         Scanner scan = new Scanner(System.in);
  8.         int lines = Integer.parseInt(scan.nextLine());
  9.         List<Person> people = new ArrayList<>();
  10.         Person man = null;
  11.         for (int i = 0; i < lines; i++) {
  12.             String[] line = scan.nextLine().split(" ");
  13.             String fname = line[0];
  14.             String sname = line[1];
  15.             int age = Integer.parseInt(line[2]);
  16.             man = new Person(fname, sname, age);
  17.             people.add(man);
  18.         }
  19.         people.sort((fperson, sperson) -> {
  20.             int comp = fperson.getFname().compareTo(sperson.getFname());
  21.             if (comp != 0){
  22.                 return comp;
  23.             }else {
  24.                 return Integer.compare(fperson.getAge(), sperson.getAge());
  25.             }
  26.         });
  27.         for (Person person : people) {
  28.             System.out.println(person.toString());
  29.         }
  30.     }
  31. }
  32. -----------------------------------------------------------------------------------
  33. package DPM;
  34. public class Person {
  35.     private String fname;
  36.     private String sname;
  37.     private int age;
  38.     public Person(String fname, String sname, int age){
  39.         this.fname=fname;
  40.         this.sname=sname;
  41.         this.age=age;
  42.     }
  43.     public void setFname(){
  44.         this.fname=fname;
  45.     }
  46.     public void setSname(){
  47.         this.sname=sname;
  48.     }
  49.     public void setAge(){
  50.         this.age=age;
  51.     }
  52.     public String getFname(){
  53.         return fname;
  54.     }
  55.     public String getSname(){
  56.         return sname;
  57.     }
  58.     public int getAge(){
  59.         return age;
  60.     }
  61.     @Override
  62.     public String toString() {
  63.         return String.format("%s %s is %d years old.",
  64.                 this.getFname(), this.getSname(), this.getAge());
  65.     }
  66. }
RAW Paste Data