How to convert array to set in Java

3 Answers

0 votes
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
  
public class MyClass {
    public static void main(String args[]) {
        String arr[] = { "java", "c", "c++", "python", "c#", "c#", "c", "c" };
  
        Set<String>set = new HashSet<>(Arrays.asList(arr));
          
        System.out.println(set);
    }
}
  
  
  
/*
run:
  
[c#, c++, python, java, c]
  
*/

 



answered May 18, 2020 by avibootz
edited May 9, 2024 by avibootz
0 votes
import java.util.Set;
import java.util.Arrays;
import java.util.stream.Collectors; 
 
public class MyClass {
    public static void main(String args[]) {
        String array[] = { "java" , "c", "c++", "php", "c#", "c#", "java" };
                                   
        Set<String> set =  Arrays.stream(array).collect(Collectors.toSet()); 
  
        System.out.println(set);
    }
}
   
   
   
/*
run:
   
[c#, c++, java, c, php]
   
*/

 



answered May 18, 2020 by avibootz
edited May 9, 2024 by avibootz
0 votes
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
 
public class MyClass {
    public static void main(String args[]) {
        Integer[] arr = { 4, 9, 0, 3, 8, 7, 4, 4, 1, 1, 3, 3 };
     
        Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
         
        System.out.println(set);
    }
}
 
 
 
/*
run:
 
[0, 1, 3, 4, 7, 8, 9]
 
*/

 



answered May 9, 2024 by avibootz

Related questions

1 answer 177 views
1 answer 171 views
1 answer 175 views
3 answers 257 views
1 answer 924 views
2 answers 125 views
125 views asked Aug 15, 2024 by avibootz
2 answers 150 views
150 views asked Nov 11, 2023 by avibootz
...