我有以下内容(简化了我的真实类(class))HashMap<User, Counter>
和
class User {
private String name;
private Integer age;
}
class Counter {
private Integer numberOfQuestions;
private Long maxQuestionId;
}
我想找出最低年龄的问题总数。
例如
UserA, 20 -> 11, 100L;
UserB, 25 -> 15, 100L;
UserC, 23 -> 30, 100L;
UserD, 20 -> 11, 100L,
UserE, 25 -> 15, 100L;
结果应该是22 -> 每个年龄的最小问题数之和(年龄:20,nOfQuestions 11+11=22)
我尝试使用 java 流:
Integer min = userQuestionHashMap.entrySet().stream()
// not working .collect(groupingBy(Map.Entry::getKey::getAge),
summingInt(Map.Entry::getValue::getNumOfQuestion))
)
// missing
.mapToInt(value -> value.getValue().getNumOfQuestion())
.min().orElse(0);
最佳答案
您可以按用户年龄分组并使用 summingInt
作为下游。然后通过key从result map中找到min:
Integer sum = map.entrySet().stream()
.collect(groupingBy(entry -> entry.getKey().getAge(),
summingInt(value -> value.getValue().getNumberOfQuestions())))
.entrySet().stream()
.min(Map.Entry.comparingByKey())
.orElseThrow(RuntimeException::new)
.getValue();
关于java - 分组以找到最小流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60541882/