在Java 8中使用数组流计算单词出现次数

时间:2018-05-04 09:19:51

标签: java arrays java-8 java-stream

如何使用数组流计算字符串中的字频?我正在使用Java 8。

这是我的代码:

String sentence = "The cat has black fur and black eyes";
String[] bites = sentence.trim().split("\\s+");

String in = "black cat";

在句子中计算单词“black”和“cat”频率。单词“黑色”频率为2,单词“cat”为1。

所以目标输出是3。

8 个答案:

答案 0 :(得分:7)

怎么样

Map<String, Long> counts = yourStringStream
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

这为您提供了从所有单词到其频率计数的映射。

答案 1 :(得分:4)

Map<String, Long> count = Arrays.stream(bites)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

答案 2 :(得分:2)

String sentence = "The cat has black fur and black eyes";
String[] bites = sentence.trim().split("\\s+");

Map<String, Long> counts = Arrays.stream(bites)
       .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

答案 3 :(得分:2)

虽然许多示例显示了如何使用流来完成它们很棒。您仍然不应忘记Collections已经有一种方法可以帮助您:

List<String> list = Array.asList(bites);
System.out.println(Collections.frequency(list, "black")); // prints 2
System.out.println(Collections.frequency(list, "cat"));   // prints 1

答案 4 :(得分:1)

如果我能理解您的问题,您可以使用此解决方案来获得预期结果:

String sentence = "The cat has black fur and black eyes";
String in = "black cat";

List<String> bites  = Arrays.asList(sentence.trim().split("\\s+"));
List<String> listIn = Arrays.asList(in.split("\\s"));

long count = bites.stream().filter(listIn::contains).count();

<强>输出

3

答案 5 :(得分:1)

    String sentence = "The cat has black fur and black eyes";
    String[] bites = sentence.trim().split("\\s+");
    String in = "black cat";
    long i = Stream.of(bites).filter(e->(Arrays.asList(in.split("\\s")).contains(e))).count();
    System.out.println(i);

答案 6 :(得分:0)

另一种简单的方法是使用java 8中引入的computeIfAbsent

et.setOnTextChangedListener(object : OnTextChangedListener {
    override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {
        foo()
    }
})

<强>输出

HashMap<String,LongAdder> wordCount= new LinkedHashMap<>(); for (String word:sentence.split("\\s")){ wordCount.computeIfAbsent(word, (k) -> new LongAdder()).increment(); }

答案 7 :(得分:0)

final Collection<String> ins = Arrays.asList(in.split("\\s+"));

Arrays.stream(bites)
    .filter(ins::contains)
    .mapToLong(bite => 1L)
    .sum()