Paul
Paul

Reputation: 17

Sort stream of objects and get first and print out

Im writing code to sort person list by age, and prefix to oldest one and print it

Defined list of objects:

    Person person1 = new Person(40,"John", "Smith");
    Person person2 = new Person(45,"Mike", "Well");
    Person person3 = new Person(68,"Bob", "Parks");
    Person person4 = new Person(49,"Leon", "Foo");
    Person person5 = new Person(30,"Christian", "Markus");

    List<Person> personList = new ArrayList<>();
    personList.add(person1);
    personList.add(person2);
    personList.add(person3);
    personList.add(person4);
    personList.add(person5);

Im able to sort and add prefix it but the problem is to get first item and print it out

    List<Person> orderedPersonAge  = personList
            .stream()
            .sorted(Comparator.comparing(Person::getAge).reversed())
            .map(s-> new 
    Person(s.getAge(),"Super"+s.getName(),s.getSureName()))
            .collect(Collectors.toList());
    System.out.println(orderedPersonAge);

I tried play with findFirst() ...

different way would be to sort by age, take the oldest one and than add prefix...

Upvotes: 0

Views: 986

Answers (2)

talex
talex

Reputation: 20544

You can either do

Person orderedPersonAge  = personList
        .stream()
        .sorted(Comparator.comparing(Person::getAge).reversed())
        .map(s-> new Person(s.getAge(),"Super"+s.getName(),s.getSureName()))
        .collect(Collectors.toList())
        .get(0);
System.out.println(orderedPersonAge);

or

Person orderedPersonAge  = personList
        .stream()
        .sorted(Comparator.comparing(Person::getAge).reversed())
        .map(s-> new Person(s.getAge(),"Super"+s.getName(),s.getSureName()))
        .findFirst()
        .get();
System.out.println(orderedPersonAge);

Upvotes: 2

Naman
Naman

Reputation: 32028

You might just be looking for

personList.stream()
   .max(Comparator.comparing(Person::getAge)) // solves for sort with reverse and find first
   .map(s -> new Person(s.getAge(), "Super" + s.getName(), s.getSurname())) // map if present
   .ifPresent(System.out::println); // print the mapped output if present

Upvotes: 0

Related Questions