【问题标题】:How to remove comma from HashSet String java如何从HashSet String java中删除逗号
【发布时间】:2022-01-18 06:29:32
【问题描述】:

我有一个 HashSet 字符串 ['a','b','c']。如何打印字符串abc

我的代码:

import java.util.*;
public class Main
{
    public static void main(String[] args) {

        HashSet<Character>h=new HashSet<>();
        h.add('a');
        h.add('b');
        h.add('c');

        // if here i am print HashSet element then print 

        System.out.println(h); //[a,b,c]

       // now i HashSet convert in String 

        String res=h.toString();    

        // when i try to print String then print [a,b,c]

        System.out.println(res);        // [a,b,c] 
      //but i am not interest in this result becuase i wnat to print only  abc remove all brackets [] ,and , commas 
}

【问题讨论】:

  • 什么是“HashSet 字符串?”请在此处包含一些实际的 Java 代码。
  • 这个字符串是通过在HashSet 上调用toString() 产生的吗?如果是这样,请不要这样做,而是通过连接不带逗号的值自己构造字符串。
  • 您是否在问如何从HashSettoString() 的结果中删除逗号,例如"['a','b','c']"?

标签: java string data-structures


【解决方案1】:

你只需要使用 String.join() 如下

System.out.println(String.join("",h));

【讨论】:

    【解决方案2】:

    如果您使用 Java 8 或更高版本,则可以使用 Java Stream APIIterable.forEach()

    public class HashSetExample {
        public static void main(String[] args) {
            Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c", "d", "e"));
            System.out.println("System.out.println(set): " + set);
            System.out.print("Using .forEach() method: ");
            set.forEach(System.out::print);
            System.out.println();
            System.out.print("Using Stream API: ");
            set.stream().forEach(System.out::print);
            System.out.println();
        }
    }
    

    输出将是:

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 2022-11-13
      • 2018-08-31
      相关资源
      最近更新 更多