如何编写java程序只打印字符串中的重复字符?

如何编写java程序只打印字符串中的重复字符?,java,arrays,collections,set,Java,Arrays,Collections,Set,我只想使用集合(集合)打印字符串中的重复字符 我已经编写了代码,但是如果字符串是“ashish”,它将显示正确的结果,但是如果字符串是“ashish java”,它将失败,因为字符“a”出现了三次 public class DuplicateStringMethod { public static void duplicateString(String str) { char[] cArray = str.toCharArray(); Set<Cha

我只想使用集合(集合)打印字符串中的重复字符

我已经编写了代码,但是如果字符串是“ashish”,它将显示正确的结果,但是如果字符串是“ashish java”,它将失败,因为字符“a”出现了三次

public class DuplicateStringMethod {
    public static void duplicateString(String str) {
        char[] cArray = str.toCharArray();
        Set<Character> set = new HashSet<Character>();

        for(char c:cArray) {
            if(set.add(c)==false) {
                System.out.println(c);
            }
        }
    }

    public static void main(String[] args) {
        duplicateString("Java ashishj ");
    }
}
公共类复制方法{
公共静态无效重复字符串(字符串str){
char[]cArray=str.toCharArray();
Set=newhashset();
用于(字符c:cArray){
if(set.add(c)=false){
系统输出打印ln(c);
}
}
}
公共静态void main(字符串[]args){
重复字符串(“Java ashishj”);
}
}
它将打印
ash
。但是我想只使用
Set
界面
sh

试试:

public static void duplicateString(String str) {
    Set<Character> firstTime = new HashSet<Character>();
    Set<Character> reported = new HashSet<Character>();

    char[] cArray = str.toCharArray();
    for(char c:cArray) {
        if (!firstTime.contains(c)) {
          firstTime.add(c);
          continue;
        }
        if (reported.contains(c)) { continue; }
        reported.add(c);
        System.out.println(c);
    }
}
publicstaticvoidduplicateString(stringstr){
Set firstTime=newhashset();
Set reported=新的HashSet();
char[]cArray=str.toCharArray();
用于(字符c:cArray){
如果(!firstTime.contains(c)){
第一次。添加(c);
继续;
}
如果(reported.contains(c)){continue;}
增加(c);
系统输出打印ln(c);
}
}
多亏了霍尔格的建议,我进行了一些测试:

  • 添加:用于10000000次操作的52443260ns
  • 包含:用于10000000次操作的28209745ns

因此,上面的代码虽然不短,但速度最快。

检查此程序

public static void duplicateString(String str) {

        char[] cArray = str.replaceAll("\\s+", "").toCharArray();

        Set<Character> set = new HashSet<Character>();
        Set<Character> alreadyExistingSet = new HashSet<Character>();

        for (char c : cArray) {
            if (set.add(c) == false && alreadyExistingSet.add(c) == true) {
                System.out.print(c);
            }
        }
    }
publicstaticvoidduplicateString(stringstr){
char[]cArray=str.replaceAll(“\\s+”,“”)。toCharArray();
Set=newhashset();
Set alreadyExistingSet=newhashset();
用于(字符c:cArray){
if(set.add(c)=false&&alreadyExistingSet.add(c)=true){
系统输出打印(c);
}
}
}

您只需使用
Set
类的
add()
方法来告诉您所插入(添加)的对象是否已经是集合的一部分。当函数返回
false
时,表示当前添加的“东西”是重复的然后,将其添加到副本的
集合中。这样,重复多次的项目在新集合中只显示一次。最后,为了保存顺序,您可能需要使用
LinkedHashSet
来存储重复项

public class TestDups {

    public static void main (String[] args) {
        String str = "Java ashishj ";
        Set<Byte> myset = new TreeSet<>();
        Set<Character> dups = new LinkedHashSet<>();
        for (byte c: str.getBytes() ) {
            if (!myset.add(c)) {
                dups.add((char)c);
            }
        }

        dups.stream().forEach(System.out::print);
    }
}
公共类testdup{
公共静态void main(字符串[]args){
String str=“Java ashishj”;
设置myset=newtreeset();
Set dups=new LinkedHashSet();
用于(字节c:str.getBytes()){
如果(!myset.add(c)){
重复添加((字符)c);
}
}
dups.stream().forEach(System.out::print);
}
}
上述代码的输出为“ash”。请注意结尾处的空白,因为原始字符串包含两个空格(单词之间和结尾)。

publicstaticvoidmain(String[]args){
字符串s=“Javaashishj”;
char[]cArray=s.toCharArray();
Set=newhashset();
用于(字符c:cArray){
如果(!set.contains(c)){
增加(c);
系统输出打印ln(c);
}
}
}

您可以在此处使用String.split()。此方法根据提供的正则表达式将字符串拆分为字符串数组。我们将使用“”,因为我们希望在每个字符后分割字符串,然后将结果输入到流中

public static void duplicateString( String str ) {

    // collect all characters in a map, whose String value is the character and whose key value is the count of occurrences in the string
    Map<String,Long> charCountMap = Arrays.stream( str.split( "" ) )
            .filter( charInString -> !charInString.equals( " " ) ) // don't want spaces
            .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) );

    charCountMap.entrySet()
            .stream()
            .filter( entrySet -> entrySet.getValue() > 1 ) // filter out occurrences that are one or less
            .forEach( entrySet -> System.out.println( String.format( "Char %s appeared %d times", entrySet.getKey(), entrySet.getValue() ) ) );
}
publicstaticvoidduplicateString(stringstr){
//收集映射中的所有字符,其字符串值为字符,其键值为字符串中出现的次数
Map charCountMap=Arrays.stream(str.split(“”)
.filter(charInString->!charInString.equals(“”)//不需要空格
.collect(Collectors.groupingBy(Function.identity()、Collectors.counting());
charCountMap.entrySet()
.stream()
.filter(entrySet->entrySet.getValue()>1)//过滤掉一个或更少的事件
.forEach(entrySet->System.out.println(String.format(“字符%s出现了%d次”,entrySet.getKey(),entrySet.getValue()));
}

我不完全清楚“仅使用
集合
界面”需要什么,但我假设这意味着重复字符将在
集合
中返回。有几种方法可以做到这一点。第一个是直接循环输入字符串的字符。它利用了
Set的功能。添加
,如果集合被修改,则返回
true
;如果集合未被修改,则返回
false
;这意味着返回
false
add
操作是重复的

static Set<Character> dups0(String input) {
    Set<Character> dups = new HashSet<>();
    Set<Character> seen = new HashSet<>();
    for (char ch : input.toCharArray()) {
        if (! seen.add(ch)) {
            dups.add(ch);
        }
    }
    return dups;
}
注意,这在映射的值集合视图上使用集合批量变异操作。为了确保映射是可变的,我使用了
groupingBy
的三个arg重载来指定映射的实现类型

如果你不喜欢突变,有一种纯粹的方法可以做到这一点:

static Set<Character> dups3(String input) {
    Map<Character, Long> map = input.chars()
                                    .mapToObj(i -> (char)i)
                                    .collect(groupingBy(ch -> ch, counting()));
    return map.entrySet().stream()
              .filter(entry -> entry.getValue() > 1)
              .map(Map.Entry::getKey)
              .collect(toSet());
}
静态设置dups3(字符串输入){
Map=input.chars()
.mapToObj(i->(char)i)
.collect(分组方式(ch->ch,counting());
返回map.entrySet().stream()
.filter(条目->条目.getValue()>1)
.map(map.Entry::getKey)
.收集(toSet());
}
再使用一个集合来存储重复的元素并打印该元素。 试着这样做:

publicstaticvoidduplicateString(stringstr){
str=str.replaceAll(“,”);
char[]cArray=str.toCharArray();
Set=newhashset();
Set set1=新的HashSet();
用于(字符c:cArray){
if(set.add(c)=false){
如果(设置1.添加(c)
static Set<Character> dups1(String input) {
     Set<Character> seen = new HashSet<>();
     return input.chars()
                 .mapToObj(ch -> (char)ch)
                 .filter(ch -> !seen.add(ch))
                 .collect(toSet());
}
static Set<Character> dups2(String input) {
     Map<Character, Long> map = input.chars()
                                     .mapToObj(i -> (char)i)
                                     .collect(groupingBy(ch -> ch, HashMap::new, counting()));
     map.values().removeIf(v -> v == 1);
     return map.keySet();
}
static Set<Character> dups3(String input) {
    Map<Character, Long> map = input.chars()
                                    .mapToObj(i -> (char)i)
                                    .collect(groupingBy(ch -> ch, counting()));
    return map.entrySet().stream()
              .filter(entry -> entry.getValue() > 1)
              .map(Map.Entry::getKey)
              .collect(toSet());
}
public static void duplicateString(String str) {
        str=str.replaceAll(" ","");
        char[] cArray = str.toCharArray();
        Set<Character> set = new HashSet<Character>();
        Set<Character> set1 = new HashSet<Character>();
        for(char c:cArray) {
            if(set.add(c)==false) {
                if(set1.add(c) == true)
                    System.out.println(c);
            }
        }
    }