List<String> gasList = // create list with duplicates... Set<String> uniqueGas = new HashSet<String>(gasList); System.out.println("Unique gas count: " + uniqueGas.size());
uniqueGas.toArray(new String[0]);
1 2 3 4
String[] unique = new HashSet<String>(Arrays.asList(array)).toArray(new String[0]); and shorter and simpler in java 8:
import java.util.*; classGFG{ publicstaticvoidmain(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using List.remove() // Repeatedly call remove() till all null are removed while (list.remove(null)) { } // Print the list System.out.println("Modified List: " + list); } }