【问题标题】:How to find count of word in Java 8如何在 Java 8 中查找字数
【发布时间】:2022-07-13 22:17:57
【问题描述】:

下面这句话

Hello world Hello Stackoverflow

预期输出:(顺序无关)

{2=Hello, 1=world, 1=Stackoverflow}

尝试使用以下代码:

        final String input = "Hello world Hello Stackoverflow";

        final Map<String, Long> output = Arrays.stream(input.split(" "))
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(output);

得到以下输出:

{world=1, Hello=2, Stackoverflow=1}

我想在 Map 中获取 Long 作为键和 String 作为值

如何做到这一点?

【问题讨论】:

  • Map 中的键是唯一的。所以没有办法得到一个看起来像{2=Hello, 1=world, 1=Stackoverflow}Map,其中有两个条目,键为1

标签: java string java-8 counting


【解决方案1】:

如何交换keyvalue

 final Map<Long, String> output = Arrays.stream(input.split(" "))
            .collect(Collectors.groupingBy(Collectors.counting(), Function.identity()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    相关资源
    最近更新 更多