Showing posts with label Set. Show all posts
Showing posts with label Set. Show all posts

Convert ArrayList To Set in Java


import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ConvertArrayList2Set {
    /**
     * Conversion from a List to a Set, 
     * or from an ArrayList to a HashSet object
     */
    public static void main(String[] args) {
        List<Object> list= new ArrayList<Object>();
        list.add("JavaStuff");
        list.add(new Long(15));
        list.add(new Integer(6));
        list.add(new Date());
        Set<Object> set = new HashSet<Object>(list);
        for (Object obj : set)
        System.out.println(obj);
    }
}

Convert Arrays to Set in Java


First Covert arrays to  java.util.List using Arras.asList( ) Method. then pass the list object as parameter while creating a Set.

import java.util.*;
public class ConvertArrayToSet {
    public static void main(String[] args) {
        Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};

        List list = Arrays.asList(numbers);
        Set set = new HashSet(list);

       for (Iterator iterator = set.iterator(); iterator.hasNext();) {
            Object o = iterator.next();
            System.out.print(o + ", ");
        }
    }
}


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email