java怎么找出重复的字符串

48次阅读
没有评论

共计 783 个字符,预计需要花费 2 分钟才能阅读完成。

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

具体步骤如下:

  1. 创建一个 HashMap 对象,键为字符串,值为该字符串在输入中出现的次数。
  2. 遍历输入的字符串数组或列表。
  3. 对于每个字符串,检查它是否已经在 HashMap 中存在。
    • 如果存在,则将该字符串的次数加 1。
    • 如果不存在,则将该字符串作为键加入 HashMap,并将其次数设置为 1。
  4. 最后,遍历 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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-12发表,共计783字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)