我收集了以下内容:
Name Age Salary
John 30 $1000
Mary 25 $2000
Eric 22 $5000
如何找到最低年龄,工资和最高年龄,薪水?
答案 0 :(得分:3)
假设您使用的是Collection个自定义对象(比方说Person对象),您只需使用Collections API与不同的Comparator。
假设您的Person类至少包含以下三种方法:
getName()
getAge()
getSalary()
现在你可以实现一个年龄比较器:
public class AgeComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
if(p1.getAge() < p2.getAge()) return -1;
else if(p1.getAge() > p2.getAge()) return 1;
else return 0;
}
public boolean equals(Person p1, Person p2) {
return this.compare(p1, p2) == 0;
}
}
要获得最大或最小年龄的人,请使用集合:
Collections.min(myList, new AgeComparator());
Collections.max(myList, new AgeComparator());
您可以使用另一个比较AgeComparator的比较器(比如SalaryComparator),但会考虑薪水。
Collections.min(myList, new SalaryComparator());
当然,您也可以使用单个类来设置变量,而不是使用两个不同的比较器。
答案 1 :(得分:1)
由于你的帖子中没有任何信息,我将做出一些假设。
您有一个Employee
类,如下所示:
public class Employee {
private String name;
private int age;
private BigDecimal salary;
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;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
}
你有一些Collection<Employee>
这样的List
:
final List<Employee> employees = ...
现在,我还假设您拥有Java 8.要查找最早的Employee
,您可以这样做:
Optional<Employee> oldest = employees.stream().
max(Comparator.comparing(Employee::getAge));
您将看到这会返回Optional
- 这是因为employees
为空时的行为未定义。您需要定义自己的行为。
与其他属性类似:
Optional<Employee> youngest = employees.stream().
min(Comparator.comparing(Employee::getAge));
Optional<Employee> highestEarner = employees.stream().
max(Comparator.comparing(Employee::getSalary));
Optional<Employee> lowestEarner = employees.stream().
min(Comparator.comparing(Employee::getSalary));
答案 2 :(得分:1)
您可以为每个字段设置比较器
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class NameAgeSalary {
private String name;
private Integer age;
private Float salary;
private NameAgeSalary(String name, Integer age, Float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return "NameAgeSalary [name=" + this.name + ", age=" + this.age
+ ", salary=" + this.salary + "]";
}
public static void main(String[] args) {
NameAgeSalary n1 = new NameAgeSalary("John",30,1000f);
NameAgeSalary n2 = new NameAgeSalary("Mary",25,2000f);
NameAgeSalary n3 = new NameAgeSalary("Eric",22,5000f);
List<NameAgeSalary> list = Arrays.asList(n1,n2,n3);
Collections.sort(list, new Comparator<NameAgeSalary>() {
@Override
public int compare(NameAgeSalary o1, NameAgeSalary o2) {
/*
* uncomment the field you want to compare
*/
return o1.age.compareTo(o2.age);
// return o1.name.compareTo(o2.name);
// return o1.salary.compareTo(o2.salary);
}
});
System.out.println("MIN "+list.get(0)); //min
System.out.println("MAX "+list.get(list.size()-1)); //max
}
}