Posted in

Write a program to list the persons whose age is greater than 18 (voter) and sort them by age.

package com.learnwithrup;

public class Person {
	private int id;
	private String name;
	private int age;

	public Person(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}
package com.learnwithrup;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class EmployeeFilterExample {

	public static void main(String[] args) {
		List<Person> employees = new ArrayList<>();
		employees.add(new Person(1, "rahul", 12));
		employees.add(new Person(2, "rajan", 19));
		employees.add(new Person(3, "rajaram", 13));
		employees.add(new Person(4, "sanjay", 18));
		employees.add(new Person(5, "sudheer", 21));
		employees.add(new Person(6, "akhilesh", 50));

		List<Person> eligibleForvote = employees.stream()
				.filter(p -> p.getAge() >= 18)
				.sorted(Comparator.comparing(Person::getAge)).toList();
		eligibleForvote.forEach(System.out::println);

	}
}

Output:

Person [id=4, name=sanjay, age=18]
Person [id=2, name=rajan, age=19]
Person [id=5, name=sudheer, age=21]
Person [id=6, name=akhilesh, age=50]

Leave a Reply

Your email address will not be published. Required fields are marked *