Java - Converting Array to Set

Posted on October 23, 2016


In this section, we will show you how to convert an array of strings into the Set. We can achieve this by using

  • For-each loop
  • Arrays.asList() method ( array⇒list⇒set)
  • Collections.addAll() method

ArrayToSetExample.java

package com.boraji.tutorial;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author imssbora
 *
 */
public class ArrayToSetExample {
	public static void main(String[] args) {
		
		/* Array  to be converted */ 
		String[] numbers=new String[]{"One","Two","Three","One","Six"};
		
		/* Method - 1 */
		Set<String> numberList1=new HashSet<>();
		for (String integer : numbers) {
			numberList1.add(integer);
		}
		System.out.println("Number List1="+numberList1);
		
		/* Method - 2 */
		Set<String> numberList2=new HashSet<>(Arrays.asList(numbers));
		System.out.println("Number List2="+numberList2);

		/* Method - 3 */
		Set<String> numberList3=new HashSet<>();
		Collections.addAll(numberList3, numbers);
		System.out.println("Number List3="+numberList3);
	}
}

Output

Number List1=[Six, One, Two, Three]
Number List2=[Six, One, Two, Three]
Number List3=[Six, One, Two, Three]