我正在申請filter,如果他在目標名單max上List<Person>,試圖找出可疑名單中最年長的人(人)
List<String> targetNames= new ArrayList<>();
targetPersonName.add("Jason");
targetPersonName.add("Mike");
List<Person> suspectedList = getSuspectedPeople();
List<Person> result = suspectedList.stream()
.filter((Person p) -> targetNames.contains(p.getName()))
.collect(Collectors.groupingBy(Person::getAge))
.entrySet().stream().max(Map.Entry.comparingByKey()).get().getValue();
上面的代碼在result不是null或不是時都能正常作業empty;但是,它提高了NoSuchElementException("No value present")何時result為空。尋找一種使用ifPresent()方法get().getValue()。
uj5u.com熱心網友回復:
您可以使用 orElse 函式并將其設定為帶有空串列的條目
.orElse(new AbstractMap.SimpleEntry<>(0, Collections.emptyList())).getValue()
所以 Java 8 中的完整函式看起來像這樣
List<Person> result = suspectedList.stream()
.filter((Person p) -> targetNames.contains(p.getName()))
.collect(Collectors.groupingBy(Person::getAge))
.entrySet().stream().max(Map.Entry.comparingByKey()).orElse(new AbstractMap.SimpleEntry<>(0, Collections.emptyList())).getValue();
結果的值將是 EmptyList
uj5u.com熱心網友回復:
您可以保存Optional到變數,然后檢查是否存在。
Optional<Map.Entry> optional = suspectedList.stream()
.filter((Person p) -> targetNames.contains(p.getName()))
.collect(Collectors.groupingBy(Person::getAge))
.entrySet().stream().max(Map.Entry.comparingByKey());
if (optional.isPresent()) {
List<Person> result = optional.get().getValue();
}
或者,如果為空,您可以使用Optional.orElse()提供默認值。或Optional.orElseGet()計算默認值,如果為空。或者Optional.orElseThrow()拋出自定義例外,如果您的用例需要它,如果為空。
List<Person> result = suspectedList.stream()
.filter((Person p) -> targetNames.contains(p.getName()))
.collect(Collectors.groupingBy(Person::getAge))
.entrySet().stream().max(Map.Entry.comparingByKey())
.orElseGet(() -> generate default value)
.getValue();
或Optional.map(),僅當可選中有值時才會應用該函式。
List<Person> result = suspectedList.stream()
.filter((Person p) -> targetNames.contains(p.getName()))
.collect(Collectors.groupingBy(Person::getAge))
.entrySet().stream().max(Map.Entry.comparingByKey())
.map(entry -> entry.getValue())
.orElseGet(ArrayList::new);
uj5u.com熱心網友回復:
如果最大條目不存在,您可以使用map將條目轉換為串列并回傳一個空串列。orElseGet
List<Person> result = suspectedList.stream()
.filter(p -> targetNames.contains(p.getName()))
.collect(Collectors.groupingBy(Person::getAge))
.entrySet()
.stream()
.max(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.orElseGet(ArrayList::new);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527496.html
標籤:爪哇java流
