简体   繁体   中英

How to remove comma from HashSet String java

Like i have HashSet String ['a','b','c'] How i print only String abc Anyone please provide the approach .

Please Observe my below code:

Java Code:

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 

}

You just have to use String.join() as followed

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

If you are using Java 8 or later then you can use Java Stream API , or Iterable.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();
    }
}

The output will be:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM