3 回答

TA貢獻1853條經驗 獲得超6個贊
您可以使用 aFunction轉換A為Double,例如:
List<A> getTopItems(List<A> elements, Function<A, Double> mapper, int n) {
return elements.stream()
.filter(a -> null != mapper.apply(a))
.sorted(Comparator.<A>comparingDouble(a -> mapper.apply(a))
.reversed())
.limit(n)
.collect(Collectors.toList());
}
您可以使用以下方式調用它:
List<A> top10BySalary = getTopItems(list, A::getSalary, 10);
List<A> top10ByAge = getTopItems(list, A::getAge, 10);
如果您的 getter 預計始終返回非 null,那么這ToDoubleFunction是一個更好的使用類型(但如果您的返回值可能為 null,則它將不起作用Double):
List<A> getTopItems(List<A> elements, ToDoubleFunction<A> mapper, int n) {
return elements.stream()
.sorted(Comparator.comparingDouble(mapper).reversed())
.limit(n)
.collect(Collectors.toList());
}

TA貢獻1854條經驗 獲得超8個贊
您可以將字段名稱傳遞給通用 getTopItems 函數并使用java.beans.PropertyDescriptor
List<A> getTopItemsByField(List<A> elements, String field) {
PropertyDescriptor pd = new PropertyDescriptor(field, A.class);
Method getter = pd.getReadMethod();
return elements.stream()
.filter(a -> getter(a) != null)
.sorted(Comparator.comparingDouble(a->a.getter(a)).reversed())
.limit(n)
.collect(Collectors.toList());
}

TA貢獻1804條經驗 獲得超2個贊
我認為你可以更改函數名稱并添加 if 條件:
List<A> getTopItems(List<A> elements, int n, String byWhat) {
if (byWhat.equals("Salary"))
return elements.stream()
.filter(a -> a.getSalary() != null)
.sorted(Comparator.comparingDouble(A::getSalary).reversed())
.limit(n)
.collect(Collectors.toList());
if (byWhat.equals("Height"))
return elements.stream()
.filter(a -> a.getHeight() != null)
.sorted(Comparator.comparingDouble(A::getHeight).reversed())
.limit(n)
.collect(Collectors.toList());
if (byWhat.equals("Age"))
return elements.stream()
.filter(a -> a.getAge() != null)
.sorted(Comparator.comparingDouble(A::getAge).reversed())
.limit(n)
.collect(Collectors.toList());
}
添加回答
舉報