Convert array to Set

In this chapter you will learn:

  1. Convert array to set

Convert array to set

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*from ja  v a  2  s .c om*/
public class Main {
  public static <T> Set<T> toSet(T... objects) {
    Set<T> theSet = new HashSet<T>();
    addToCollection(theSet, objects);
    return theSet;
  }

  public static <T> List<T> toList(T... objects) {
    List<T> theSet = new ArrayList<T>();
    addToCollection(theSet, objects);
    return theSet;
  }

  private static <T> void addToCollection(Collection<T> theCollection,
      T... objects) {
    for (T object : objects) {
      theCollection.add(object);
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to fill value to an array
  2. Fill an array of boolean value
Home » Java Tutorial » Array
Java Array
Create an Array
Array Index and length
Multidimensional Arrays
Array examples
Array copy
Array compare
Array Binary search
Array Search
Array sort
Array to List
Convert array to Set
Array fill value
Array to String
Array element reverse
Array element delete
Array shuffle
Array element append
Array min / max value
Sub array search
Get Sub array
Array dimension reflection
Array clone