[英]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.