温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java字符串的去重方法

发布时间:2025-08-13 05:38:49 来源:亿速云 阅读:126 作者:小樊 栏目:编程语言

在Java中,有多种方法可以对字符串进行去重。以下是一些常见的方法:

方法一:使用LinkedHashSet

LinkedHashSet可以保持插入顺序,并且不允许重复元素。

import java.util.LinkedHashSet;
import java.util.Set;

public class StringDeduplication {
    public static String removeDuplicates(String str) {
        Set<Character> set = new LinkedHashSet<>();
        StringBuilder sb = new StringBuilder();
        
        for (char c : str.toCharArray()) {
            if (set.add(c)) { // add() returns true if the element was not already present
                sb.append(c);
            }
        }
        
        return sb.toString();
    }

    public static void main(String[] args) {
        String input = "hello world";
        String result = removeDuplicates(input);
        System.out.println(result); // Output: helo wrd
    }
}

方法二:使用StringBuilder和HashSet

这种方法通过遍历字符串并将字符添加到HashSet中来去重,然后使用StringBuilder构建结果字符串。

import java.util.HashSet;
import java.util.Set;

public class StringDeduplication {
    public static String removeDuplicates(String str) {
        Set<Character> set = new HashSet<>();
        StringBuilder sb = new StringBuilder();
        
        for (char c : str.toCharArray()) {
            if (set.add(c)) {
                sb.append(c);
            }
        }
        
        return sb.toString();
    }

    public static void main(String[] args) {
        String input = "hello world";
        String result = removeDuplicates(input);
        System.out.println(result); // Output: helo wrd (order may vary)
    }
}

方法三:使用Java 8 Stream API

Java 8引入了Stream API,可以更简洁地实现字符串去重。

import java.util.stream.Collectors;

public class StringDeduplication {
    public static String removeDuplicates(String str) {
        return str.chars()
                   .distinct()
                   .mapToObj(c -> String.valueOf((char) c))
                   .collect(Collectors.joining());
    }

    public static void main(String[] args) {
        String input = "hello world";
        String result = removeDuplicates(input);
        System.out.println(result); // Output: helo wrd
    }
}

方法四:使用正则表达式

这种方法适用于去除连续重复的字符。

public class StringDeduplication {
    public static String removeConsecutiveDuplicates(String str) {
        return str.replaceAll("(.)\\1+", "$1");
    }

    public static void main(String[] args) {
        String input = "hellooo world";
        String result = removeConsecutiveDuplicates(input);
        System.out.println(result); // Output: helo world
    }
}

选择哪种方法取决于你的具体需求,例如是否需要保持原始顺序、是否处理连续重复字符等。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手