我正在尝试使用 java 流来实现与下面相同的逻辑。基本上我试图找出一个集合中是否有 2 个条目多次具有相同的日志 id 和标签
class Log {
private String id;
private List<String> tags;
};
void findLogsWithSameTag(List<Log> logs) {
final Map<String, Map<String, Integer>> map = new HashMap<>();
for ( var log : logs ) {
for ( var tag : log.getTags() ) {
Integer count = map.computeIfAbsent( log.getId(), key -> new HashMap<>())
.getOrDefault( tag, 0);
map.get( log.getId() ).put( tag, count + 1 );
}
}
for ( final var entry : map.entrySet() ) {
for ( final var entry2 : entry.getValue().entrySet() ) {
if ( entry2.getValue() > 1 ) {
throw new IllegalArgumentException("bad!");
}
}
}
}
我首先尝试按标签对
Log
进行分组,但我不知道如何将flatMap
键设置为String
而不是List<String>
。然后我尝试按 Log::getId
进行分组,但我再次无法将 flatMap
tags
分组为 String
。
有人知道如何用
stream().groupingBy(...)
做到这一点吗?
编辑:添加一些示例:
// should throw as log1 has tag1 twice
List.of(
new Log("log1", List.of( "tag1", "tag2") )
new Log("log1", List.of( "tag1") )
);
// should not throw as there is no tag more than once associated with an id
List.of(
new Log("log1", List.of( "tag1", "tag2") )
new Log("log2", List.of( "tag1") )
);
“我有 2 个具有相同日志 ID 的条目”
为什么两个条目会有相同的 id?