Sachin
Sachin

Reputation: 459

pick an element from a Set based on its property

Set<Employee> employeeSet = 

How can I pick the oldest Employee from the Set (it has a property 'int age')

Upvotes: 0

Views: 57

Answers (5)

Architkumar Patel
Architkumar Patel

Reputation: 71

You can define first Age for find oldest employee int baseAge = 50; Now you need to compare all employee age to this Age

  Public Set findOldest()
    {
        int baseAge =50;
        Set < Employee > oldest = new HashSet< Employee >();
        Set<Employee> employee = // your set of employees
        for ( Employee emp : employee )
        {
            If(emp.empAge > baseAge)
                    oldest.add(emp);
        }
        return oldest;
    }

Upvotes: 0

Varun Pozhath
Varun Pozhath

Reputation: 626

You can iterate through the collection.

int maxAge = 0; //  
for(Employee emp: employeeSet){
    if(emp.getAge() > maxAge)
      maxAge = employee.getAge()
}

maxAge variable will have the highest age after the forEach loop ends

Upvotes: 0

nemo
nemo

Reputation: 61

I think Stream interface in Java 8 can help

final Comparator<Employee> comp = Comparator.comparingInt(Employee::getAge);
Employee oldest = employeeList.stream()
            .max(comp)
            .get();

See detail on this https://stevewall123.wordpress.com/2014/08/31/java-8-streams-max-and-streams-min-example/

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533820

You can use the Stream API

Optional<Employee> employee = employeeSet.stream()
                                         .max(Comparator.comparing(e -> e.age));

employee.get() will return the Employee unless the set was empty.

Upvotes: 1

EthanBar
EthanBar

Reputation: 705

This may not be the best solution for performance, but you could iterate through each element using an enhanced for loop:

Employee oldest = employeeSet.get(0); // Initialize with the first index
for (Employee emp : employeeSet) {
    if (emp.age > oldest.age) {
        oldest = emp;
    }
}

Upvotes: 0

Related Questions