首页 文章

将 set 转换为带有 count 的字符串映射

提问于
浏览
-1

我的原始数据是字符串流

correctname
abc,def,ghi,jol
abc
def,ghi
zzzzzzzzzz
myname
pppppppppp
jkl

转换它集:

{correct}
{abc, def,ghi,jkl}
{abc}
{def,ghi}
{invalid}
{correct}
{invalid}
{jkl}

我有一些 Stream.map(...)让我高于结果

Map<String,Long> answer = Stream.map(...).collect(groupingby??)

现在我想收集它(收集或映射或分组)并将结果作为 Map 返回,以便我的答案应该是

地图> {更正:2 无效:另外 2 人:8}

2 回答

  • 4

    这里的诀窍是flatMap每个都设置为其中的字符串。完成后,您可以使用map将值转换为您感兴趣的值并计算它们。 E.g:

    Set<String> allowed = new HashSet<>(Arrays.asList("correct", "invalid"));
    Map<String, Long> result = 
        values.flatMap(Set::stream)
              .map(s -> allowed.contains(s) ? s : "other")
              .collect(Collectors.groupingBy(Function.identity(), 
                                             Collectors.counting()));
    
  • 2

    听起来你正在寻找这个:

    Map<String, Long> answer = sets.stream()
            .flatMap(Set::stream)
            .collect(Collectors.groupingBy(
                    s -> s.matches("invalid|correct") ? s : "others",
                    Collectors.counting()));
    

相关问题