java怎么找出重复的字符串

   2025-02-15 3110
核心提示:要找出重复的字符串,可以使用HashMap来记录每个字符串出现的次数。具体步骤如下:创建一个HashMap对象,键为字符串,值为该字符

要找出重复的字符串,可以使用HashMap来记录每个字符串出现的次数。

具体步骤如下:

创建一个HashMap对象,键为字符串,值为该字符串在输入中出现的次数。遍历输入的字符串数组或列表。对于每个字符串,检查它是否已经在HashMap中存在。如果存在,则将该字符串的次数加1。如果不存在,则将该字符串作为键加入HashMap,并将其次数设置为1。最后,遍历HashMap的所有键值对,找到出现次数大于1的字符串,即为重复的字符串。

以下是一个示例代码:

import java.util.HashMap;import java.util.Map;public class FindDuplicateStrings {    public static void main(String[] args) {        String[] strings = {"hello", "world", "hello", "java", "world"};        Map<String, Integer> stringCountMap = new HashMap<>();        for (String str : strings) {            if (stringCountMap.containsKey(str)) {                int count = stringCountMap.get(str);                stringCountMap.put(str, count + 1);            } else {                stringCountMap.put(str, 1);            }        }        for (Map.Entry<String, Integer> entry : stringCountMap.entrySet()) {            if (entry.getValue() > 1) {                System.out.println("重复字符串:" + entry.getKey());            }        }    }}

执行以上代码,输出结果为:

重复字符串:hello重复字符串:world

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言