ivana_andreevska

AV5 Oldest Person

Aug 11th, 2022
1,003
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. package AV5;
  2.  
  3. public class Person implements Comparable<Person>{
  4.     private String name;
  5.     private int age;
  6.  
  7.     public Person(String name, int age) {
  8.         this.name = name;
  9.         this.age = age;
  10.     }
  11.  
  12.     public Person(String line)
  13.     {
  14.         String[] parts=line.split("\\s+");
  15.         this.name=parts[0];
  16.         this.age=Integer.parseInt(parts[1]);
  17.     }
  18.  
  19.     @Override
  20.     public int compareTo(Person other) {
  21.         return Integer.compare(this.age , other.age);
  22.     }
  23.  
  24.     @Override
  25.     public String toString() {
  26.         return "Person{" +
  27.                 "name='" + name + '\'' +
  28.                 ", age=" + age +
  29.                 '}';
  30.     }
  31. }
  32.  
  33. package AV5;
  34.  
  35. import java.io.*;
  36. import java.util.Collections;
  37. import java.util.Comparator;
  38. import java.util.List;
  39. import java.util.stream.Collectors;
  40.  
  41. public class OldestPersonTest {
  42.     public static List<Person> readData(InputStream inputStream) {
  43.         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  44.  
  45.         return bufferedReader.lines()
  46.                 .map(line -> new Person(line))
  47.                 .collect(Collectors.toList());
  48.     }
  49.  
  50.     public static void main(String[] args) {
  51.         File file = new File("C:\\Users\\User\\Desktop\\Napredno Sept\\src\\AV5\\people");
  52.  
  53.         try {
  54.             List<Person> people = readData(new FileInputStream(file));
  55.             Collections.sort(people);
  56.             System.out.println(people.get(people.size() - 1));
  57.  
  58.            if(people.stream().max(Comparator.naturalOrder()).isPresent())
  59.            {
  60.                System.out.println(people.stream().max(Comparator.naturalOrder()).get());
  61.            }
  62.         } catch (FileNotFoundException e) {
  63.             e.printStackTrace();
  64.         }
  65.     }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment