Juho M
Juho M

Reputation: 347

Counting word occurence with arrays stream in Java 8

How I can calculate word frequency in a string with using arrays stream? I'm using Java 8.

Here is my code:

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

String in = "black cat";

calculate words "black" and "cat" frequency in the sentence. Word "black" frequency is 2 and word "cat" is 1.

So the goal output is then 3.

Upvotes: 2

Views: 5236

Answers (8)

Lino
Lino

Reputation: 19926

Although many examples showing how it's been done with streams are great. You still shouldn't forget that Collections already has a method that does this for you:

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

Upvotes: 2

marsouf
marsouf

Reputation: 1147

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

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

Upvotes: 0

Hadi
Hadi

Reputation: 17289

The other simple way is use of computeIfAbsent that introduced in java 8

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

output

{The=1, cat=1, has=1, black=2, fur=1, and=1, eyes=1}

Upvotes: 0

Eritrean
Eritrean

Reputation: 16498

    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);

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59968

If I can understand your question you can use this solution to get the expected result :

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();

Outputs

3

Upvotes: 1

Junaid Subhani
Junaid Subhani

Reputation: 41

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()));

Upvotes: 2

Thilo
Thilo

Reputation: 262494

How about

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

This gives you a Map from all words to their frequency count.

Upvotes: 8

Yazan Jaber
Yazan Jaber

Reputation: 2068

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

Upvotes: 6

Related Questions