如何制作人员列表,如果所有人员的工资总额超过 5000(例如),或者如果总工资将小于返回空列表
我尝试使用 java.util.Collection.stream()
public static List<Person> filterPositions (List<Person> persons, Predicate<Person> predicate) {
return positions.stream().filter(predicate).collect(
Collectors.collectingAndThen(Collectors.summingInt( ...
但我不知道如何继续这段代码
最佳答案
也许你想得太复杂了……
public static List<Person> filterPositions(
List<Person> persons, Predicate<Person> predicate) {
return persons.stream().filter(predicate).mapToInt(Person::getSalary).sum() > 5000?
persons: Collections.emptyList();
}
如果您想返回过滤列表,您可以使用:
public static List<Person> filterPositions(
List<Person> persons, Predicate<Person> predicate) {
return persons.stream().filter(predicate).mapToInt(Person::getSalary).sum() > 5000?
persons.stream().filter(predicate).collect(Collectors.toList()):
Collections.emptyList();
}
或
public static List<Person> filterPositions(
List<Person> persons, Predicate<Person> predicate) {
persons = persons.stream().filter(predicate).collect(Collectors.toList());
return persons.stream().mapToInt(Person::getSalary).sum() > 5000?
persons: Collections.emptyList();
}
任一变体都有优势,具体取决于条件是否为真。虽然第一变型在不是的情况下省略了收集操作,但是第二变型在是的情况下省略了第二过滤操作。因此,偏好取决于条件为真的可能性。或者过滤器有多贵,或者结果列表预计有多大。
<小时/>如果允许您修改传入列表,则会出现完全不同的选项:
/** modifies {@code persons} list. */
public static void filterPositions(
List<Person> persons, Predicate<Person> predicate) {
persons.removeIf(predicate.negate());
if(persons.stream().mapToInt(Person::getSalary).sum() <= 5000)
persons.clear();
}
关于java - 如果所有人的工资总额超过...,如何制作职位列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33017060/