Java hashset and list

How to convert List to Set (ArrayList to HashSet)

Collection object has a constructor that accept a Collection object to initial the value. Since both Set and List are extend the Collection, the conversion is quite straightforward. It’s just pass a List into Set constructor or vice verse.

Convert List to Set
Convert Set to List
 List list = new ArrayList(set); 

1. List To Set Example

 import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ConvertListToSet < public static void main( String[] args ) < System.out.println("List values . "); Listlist = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("1"); for (String temp : list) < System.out.println(temp); >Set set = new HashSet(list); System.out.println("Set values . "); for (String temp : set) < System.out.println(temp); >> > 

Output

 List values . 1 2 3 4 1 Set values . 3 2 1 4 

After the conversion, all the duplicated values in List will just ignore, because the Set does not allow duplicated values.

2. Set To List Example

 import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ConvertSetToList < public static void main( String[] args ) < System.out.println("Set values . "); Setset = new HashSet(); set.add("1"); set.add("2"); set.add("3"); set.add("4"); for (String temp : set) < System.out.println(temp); >System.out.println("List values . "); List list = new ArrayList(set); for (String temp : list) < System.out.println(temp); >> > 

Output

 Set values . 3 2 1 4 List values . 3 2 1 4 
mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Читайте также:  Правильная обработка исключений python

Источник

Convert Set to List in Java and Vice-versa

In Java, List and Set are Collections types to store elements. List is an index-based ordered collection, and Set is an unordered collection. List allows duplicate elements, but Set contains only unique elements. Both collection types are quite different and have their own usecases.

In this Java tutorial, Learn to convert a specified Set to a List. Also, learn to reverse convert List to Set, a useful method to remove duplicate elements from a list.

We will be using the following Set to List type in different ways.

1.1. Using List Constructor

To convert a given Set to a List, we can use the ArrayList constructor and pass HashSet as the constructor argument. It will copy all elements from HashSet to the newly created ArrayList.

ArrayList arrayList = new ArrayList(set); Assertions.assertEquals(3, arrayList.size());

Another useful method to get a List with Set elements is to create an empty list instance and use its addAll() method to add all the elements of the Set to List.

ArrayList arrayList = new ArrayList<>(); arrayList.addAll(set); Assertions.assertEquals(3, arrayList.size());

First, convert the Set to Stream, and then collect the Stream elements to List.

List list = set.stream().toList(); Assertions.assertEquals(3, list.size());

We might need to create a HashSet from a specified ArrayList when we want to remove duplicates from the list because sets do not allow duplicate items.

Let us begin with creating a List instance, and then we will convert it to the Set. The list contains 7 items, but only 4 unique items. So the Set size must be 4 in each method.

List list = List.of(1, 2, 3, 3, 3, 5, 5);

Similar to the previous example, we can use the constructor HashSet(collection) to convert to initialize a HashSet with the items from the ArrayList.

Set set = new HashSet(list); Assertions.assertEquals(4, set.size());

The Set.addAll(list) adds all of the elements in the specified collection to this set if they’re not already present.

Set set = new HashSet(); set.addAll(list); Assertions.assertEquals(4, set.size());

Similar to the previous section, we can convert a set to list using the Stream as follows:

Set set = list.stream().collect(Collectors.toSet()); Assertions.assertEquals(4, set.size());

Источник

Difference between ArrayList and HashSet in Java

Here are couple of differences between ArrayList and HashSet.

  1. Inheritance:
  2. Implementation: Implementation : ArrayList implements List interface while HashSet implements Set interface in Java.
  3. Internal implementation: ArrayList is backed by an Array while HashSet is backed by an HashMap.
  4. Duplicates : ArrayList allows duplicate values while HashSet doesn’t allow duplicates values.
  5. Constructor : ArrayList have three constructor which are ArrayList(), ArrayList(int capacity) ArrayList(int Collection c) while HashSet have four constructor which are HashSet(), HashSet(int capacity), HashSet(Collection c) and HashSet(int capacity, float loadFactor)
  6. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn’t maintain any order.
  7. Indexing : ArrayList is index based we can retrieve object by calling get(index) method or remove objects by calling remove(index) method while HashSet is completely object based. HashSet also does not provide get() method.
  8. Null Object: ArrayList not apply any restriction, we can add any number of null value while HashSet allow one null value.

9. Basic Operation’s Time complexity :-

9.1 ArrayList common operation’s time complexity

add() – takes O(1) time;
get() – it takes constant time O(1);
remove() –it takes linear time complexity O(n) . It iterate the entire array to find the element qualifying for removal.
contains() – It also take linear time complexity O(n).

9.2 Set common operation’s time complexity

For HashSet, the add(), remove() and contains() operations cost constant O(1) time thanks to the internal HashMap implementation.

ArrayList example

Источник

Difference between ArrayList and HashSet in Java? Answer

The main difference between ArrayList and HashSet is that one is a List implementation while the other is a Set implementation. It means all the differences between a List data structure and a Set data structure also apply to this pair. For example, List implementations are ordered, it stores the element in the order they were added, while Set implementation doesn’t provide such a guarantee. Similarly, since List provides Random access, you can access any element directly if you know the index, but Set doesn’t provide such a facility.

You need to Iterate through the whole collection to get access to any elements. We will see a couple of more differences in this Java tutorial.

By the way ArrayList and HashSet are the two most common Collection classes used in Java programming language and before discussing the difference between ArrayList vs HashSet , let’s see some similarities between them :

Similarities ArrayList and HashSet

1) Both ArrayList and HashSet are non synchronized collection classes and not meant to be used in multi-threading and concurrent environments. You can make ArrayList and HashSet synchronized by using Collections.synchroinzedCollection() just like we make ArrayList and HashSet read-only other days.

2) Both ArrayList and HashSet can be traversed using Iterator. This is in fact a preferred way if you want to perform operations on all elements.

3) Iterator of ArrayList and HashSet both are fail-fast, i.e. they will throw ConcurrentModificationException if ArrayList or HashSet is modified structurally once Iterator has been created.

Difference between ArrayList vs HashSet in Java

1. First and most important difference between ArrayList and HashSet is that ArrayList implements List interface while HashSet implements Set interface in Java.

2. Another difference between ArrayList and HashSet is that ArrayListallow duplicates while HashSet doesn’t allow duplicates. This is the side effect of first difference and property of implementing List and Set interface.

3. The differences between ArrayList and HashSet is that ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn’t maintain any order.

4. The difference between ArrayList and HashSet is that ArrayList is backed by an Array while HashSet is backed by a HashMap instance. See how HashSet internally works in Java for more details.

5. Fifth difference between HashSet and ArrayList is that it’s index-based you can retrieve objects by calling get(index) or remove objects by calling remove(index) while HashSet is completely object-based. HashSet also doesn’t provide the get() method.

Difference between ArrayList and HashSet in Java

That’s all on the difference between ArrayList and HashSet . these differences help you to decide where to use ArrayList and where to use HashSet in Java. in terms of performance between ArrayList and HashSet , choose what suits best to you. the raw array has fasted among them.

Источник

Оцените статью