Use the appropriate data structure to count the number of words

  java

Order

This article mainly describes how to use the data structure of bag of apache collections4 and multiset of guava to count the number of words.

maven

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>

bag

    @Test
    public void testBag(){
        Bag<String> bag = new HashBag<>();
        String content = "She is beautiful and she is my angel";
        Arrays.stream(content.split(" ")).forEach(word -> {
            bag.add(word);bag.add(word);
        });
        //get unique key
        Set<String> set = bag.uniqueSet();
        set.stream().forEach(word -> {
            System.out.println(word + "-->" + bag.getCount(word));
        });
    }

multiset

    @Test
    public void testMultiSet(){
        String content = "She is beautiful and she is my angel";
        Multiset<String> set = HashMultiset.create();
        Arrays.stream(content.split(" ")).forEach(word -> {
            set.add(word);
        });
        set.stream().distinct().forEach(e -> {
            System.out.println(e + "-->" + set.count(e));
        });
    }

Summary

The encapsulated data structure is very simple to use.