![](/img/trans.png)
[英]java stream groupBy collectors for null key and apply collectors on the grouped value list
[英]Can I use collectors in java to find a document with max value of a key from a list of documents
我有一個 Java 文檔的ArrayList
。 我想要具有鍵最大值的文檔,例如nameId
。 我可以使用收集器以最短的方式找到它嗎?
我的代碼工作正常,但我正在尋找更好的方法來做到這一點。
//ArrayList<Document> documents
//above is the list of documents i have
HashMap<String, Document> map = new HashMap<>();
documents.forEach(doc -> map.put(doc.getString(nameId), doc));
String maxNameId = Collections.max(map.keySet());
Document docWithMaxNameId = map.get(maxNameId);
代碼返回正確的值,但我想知道是否有另一種方法使用收集器以單行或更短的方式解決此問題。
無需收集到 HashMap:
Document docWithMaxNameId =
documents.stream()
.max(Comparator.comparing(doc -> doc.getString(nameId))
.get();
如前所述,無需收集到HashMap
。
您可能會感到驚訝,但已經有一個Collections.max
使用比較器:
Document doc = Collections.max(documents, Comparator.comparing(d -> d.getString(nameId));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.