在字符串中查找重复的单词并计算重复次数

13
我需要在一个字符串中找到重复的单词,并计算它们被重复的次数。所以,如果输入字符串是这个:
String s = "House, House, House, Dog, Dog, Dog, Dog";
我需要创建一个新的字符串列表,其中不包括重复项,并在其他地方保存每个单词的重复次数,例如:
新字符串:"House, Dog"
新整数数组:[3, 4]
有没有一种简单的方法可以使用Java轻松完成这个任务?我已经使用s.split()函数成功地将字符串分离,但是接下来该如何计算重复项并在新字符串中消除它们呢?谢谢!
29个回答

24

你已经完成了艰苦的工作。现在你可以使用一个Map来计算出现次数:

Map<String, Integer> occurrences = new HashMap<String, Integer>();

for ( String word : splitWords ) {
   Integer oldCount = occurrences.get(word);
   if ( oldCount == null ) {
      oldCount = 0;
   }
   occurrences.put(word, oldCount + 1);
}

使用map.get(word)可以告诉你一个单词出现的次数。您可以通过迭代map.keySet()来构建一个新的列表:

for ( String word : occurrences.keySet() ) {
  //do something with word
}

请注意,keySet 方法输出结果的顺序是任意的。如果您需要按照单词在输入字符串中首次出现的顺序排序,应该使用 LinkedHashMap


1
使用map.get(word)返回null。这是文档:https://docs.oracle.com/javase/7/docs/api/java/util/Map.html ----稍后编辑:我看到你的键是字符串,所以没问题,我的错。 - Immers Cherub

4
public class StringsCount{

    public static void main(String args[]) {

        String value = "This is testing Program testing Program";

        String item[] = value.split(" ");

        HashMap<String, Integer> map = new HashMap<>();

        for (String t : item) {
            if (map.containsKey(t)) {
                map.put(t, map.get(t) + 1);

            } else {
                map.put(t, 1);
            }
        }
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
            System.out.println(map.get(key));
        }

    }
}

4
尝试这个:
public class DuplicateWordSearcher {
@SuppressWarnings("unchecked")
public static void main(String[] args) {

    String text = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f";

    List<String> list = Arrays.asList(text.split(" "));

    Set<String> uniqueWords = new HashSet<String>(list);
    for (String word : uniqueWords) {
        System.out.println(word + ": " + Collections.frequency(list, word));
    }
}

}


3
正如其他人所提到的,使用String::split(),接着使用一些map(hashmap或linkedhashmap),然后合并你的结果。为了完整起见,下面是代码。
代码如下:
import java.util.*;

public class Genric<E>
{
    public static void main(String[] args) 
    {
        Map<String, Integer> unique = new LinkedHashMap<String, Integer>();
        for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) {
            if(unique.get(string) == null)
                unique.put(string, 1);
            else
                unique.put(string, unique.get(string) + 1);
        }
        String uniqueString = join(unique.keySet(), ", ");
        List<Integer> value = new ArrayList<Integer>(unique.values());

        System.out.println("Output = " + uniqueString);
        System.out.println("Values = " + value);

    }

    public static String join(Collection<String> s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }
}

新的字符串为输出 = 房子,狗

整数数组(或者更确切地说是列表)Values = [3, 4](您可以使用List :: toArray)来获取一个数组。


嗨@Favonius。我想从文本文件中加载字符串并应用您的代码,就像这样,我想获取2000多个文本文件,每个文件分别应用您的代码并获得输出...这可能吗? - Ram Ki

2
使用Java8
private static void findWords(String s, List<String> output, List<Integer> count){
    String[] words = s.split(", ");
    Map<String, Integer> map = new LinkedHashMap<>();
    Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
    map.forEach((k,v)->{
        output.add(k);
        count.add(v);
    });
}

此外,如果您想保留插入顺序,请使用LinkedHashMap。最初的回答中提到了这一点。
private static void findWords(){
    String s = "House, House, House, Dog, Dog, Dog, Dog";
    List<String> output = new ArrayList<>();
    List<Integer> count = new ArrayList<>();
    findWords(s, output, count);
    System.out.println(output);
    System.out.println(count);
}

输出

[House, Dog]
[3, 4]

1
一旦你从字符串中获取了单词,就很容易了。从Java 10开始,您可以尝试以下代码:
import java.util.Arrays;
import java.util.stream.Collectors;

public class StringFrequencyMap {
    public static void main(String... args) {
        String[] wordArray = {"House", "House", "House", "Dog", "Dog", "Dog", "Dog"};
        var freq = Arrays.stream(wordArray)
                         .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
        System.out.println(freq);
    }
}

输出:

{House=3, Dog=4}

1
如果这是一份作业,那么我只能说:使用 String.split()HashMap<String,Integer>
(我看到你已经找到了 split()。你走在正确的路上了。)

1

它可能在某种程度上对你有所帮助。

String st="I am am not the one who is thinking I one thing at time";
String []ar = st.split("\\s");
Map<String, Integer> mp= new HashMap<String, Integer>();
int count=0;

for(int i=0;i<ar.length;i++){
    count=0;

    for(int j=0;j<ar.length;j++){
        if(ar[i].equals(ar[j])){
        count++;                
        }
    }

    mp.put(ar[i], count);
}

System.out.println(mp);

0
希望这能对你有所帮助。 public void countInPara(String str) {
    Map<Integer,String> strMap = new HashMap<Integer,String>();
    List<String> paraWords = Arrays.asList(str.split(" "));
    Set<String> strSet = new LinkedHashSet<>(paraWords);
    int count;

    for(String word : strSet) {
        count = Collections.frequency(paraWords, word);
        strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word));
    }

    for(Map.Entry<Integer,String> entry : strMap.entrySet())
        System.out.println(entry.getKey() +" :: "+ entry.getValue());
}

0
/*count no of Word in String using TreeMap we can use HashMap also but word will not display in sorted order */

import java.util.*;

public class Genric3
{
    public static void main(String[] args) 
    {
        Map<String, Integer> unique = new TreeMap<String, Integer>();
        String string1="Ram:Ram: Dog: Dog: Dog: Dog:leela:leela:house:house:shayam";
        String string2[]=string1.split(":");

        for (int i=0; i<string2.length; i++)
        {
            String string=string2[i];
            unique.put(string,(unique.get(string) == null?1:(unique.get(string)+1)));
        }

        System.out.println(unique);
    }
}      

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接