Java Set interface

Introduction

A Set is an unordered Collection of unique elements.

The collections framework contains several Set implementations, including HashSet and TreeSet.

HashSet stores its elements in a hash table, and TreeSet stores its elements in a tree.

The following code uses HashSet used to remove duplicate values from array of strings.

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    // create and display a List<String>
    String[] langs = { "SQL", "SQL", "HTML", "C++", "C", "SQL", "Javascript"};
    List<String> list = Arrays.asList(langs);
    System.out.println(list);/*from   w  w w. ja  v a  2 s .co m*/
    // eliminate duplicates then print the unique values
    printNonDuplicates(list);
  }

  // create a Set from a Collection to eliminate duplicates
  private static void printNonDuplicates(Collection<String> values) {
    // create a HashSet
    Set<String> set = new HashSet<>(values);
    for (String value : set)
      System.out.println(value);
  }
}

HashSet is one of the implementation of Set.

import java.util.HashSet;
import java.util.Set;

public class FindDups {
  public static void main(String[] args) {
    Set<String> s = new HashSet<String>();
    for (String a : args)
      if (!s.add(a))
        System.out.println("Duplicate detected: " + a);

    System.out.println(s.size() + " distinct words: " + s);
  }/*w w  w.j  a  va2s  . c om*/
}



PreviousNext

Related