Organizational Research By

Surprising Reserch Topic

easily convert array to set in java


I'd like to convert an array to a set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:

java.util.Arrays.asList(Object[] a);

Any ideas?

 


asked Jun 22, 2015 in Core java by rahulgii
0 votes
66 views



Related Hot Questions

4 Answers

0 votes
 
Best answer
Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
answered Jun 22, 2015 by rahulgii
selected Jun 23, 2015 by rajesh
0 votes
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);
answered Jun 22, 2015 by rahulgii
0 votes
String[] stArr = {"first", "seccond", "third", "fourth"};

Set<String> strSet = Arrays.stream(strArr).collect(Collectors.toSet());  
System.out.println(strSet); 
answered Jun 22, 2015 by rahulgii
0 votes

Quickly : you can do :

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);
answered Jun 22, 2015 by rahulgii

...