I need to sort an array list which includes an age for each person, but I have to print out a list of people over 65. I know how to do this in SQL but not Java. Any help would be appreciated. Thanks!
2 Answers
First make sure you have the problem stated fully, then think about the algorithm you will use first (that is not language specific); then implement the algorithm.
If the problem is simply to list all people in an array whose age is over 65 (not 65 or older?), then you only need to loop through the array and, for each line, check to see if the age meets the criteria. If it does, print out the person.
If you need to sort the list, then do that first. (Use bubble sort or a more efficient sort if the list is long); then step through the list until you find the cutoff age and print out all the rest.
Comments
I'm going to assume that you (a) want to sort a list of Person objects by their age value, and then (b) print out only those Person's with an age greater than 65.
In java, one way to do the sort is to use a Comparator. The Javadoc is here. You can implement it as an inline class if you're only going to use it once, or as a separate class if you plan to use it in several places.
ArrayList<Person> persons = new ArrayList<Person>();
Comparator<Person> example = new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
};
Collections.sort(persons, example);
This implementation will sort by age. You can switch between ascending and descending order by switching o1 and o2.
Another, possibly simpler way would be to implement Comparable in your Person class.
To make your Person class comparable, modify its declaration thus:
public class Person implements Comparable<Person> {
And add the compareTo() method:
@Override
public int compareTo(Person o) {
return this.getAge() - o.getAge();
}
However, this only lets you sort the class by one attribute. With Comparator's, you can define more than one in order to sort by different attributes, such as first name, last name, and age.
To print out only Person's whose age is greater than 65, just loop through the list's contents with an if condition checking each Person's age and printing only if age > 65.
if) and then edit your question to include the code, unless you just succeed of course... in which case delete the question.persons.stream().filter(p -> p.getAge() > 65);