Home > Software engineering >  How to remove comma from HashSet String java
How to remove comma from HashSet String java

Time:01-18

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 

}

CodePudding user response:

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

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

CodePudding user response:

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:

enter image description here

  •  Tags:  
  • Related