Home > other >  Adding integer values to a set in Java
Adding integer values to a set in Java

Time:09-16

I'm new to using sets in Java, I understand the typical code for adding values to a set is:

Set<Integer> intSet = new HashSet<Integer>();

//then use add method
intSet.add(4);
intSet.add(7);
intSet.add(12);

But my question is how can I add multiple values at once, and is it possible to declare the set with its values within the HashSet<Integer>(); line? Thanks y'all!

CodePudding user response:

You can pass them as part of another Collection to the constructor (or use addAll). Like,

Set<Integer> intSet = new HashSet<>(Arrays.asList(4, 7, 12));

or if you need to add multiple lists like

Set<Integer> intSet = new HashSet<>();
intSet.addAll(Arrays.asList(4, 7, 12));

CodePudding user response:

You can use a Collection of Integers, as the constructor of HashSet accommodates for this:

Set<Integer> intSet = new HashSet<Integer>(Arrays.asList(2,7,12));

To check your code:

for(Integer i: intSet){
  System.out.print(i   " ");
}

Output:

2 7 12 

CodePudding user response:

The Answer by Elliott Frisch is correct for modifiable sets.

Unmodifiable sets

You asked:

is it possible to declare the set with its values within the HashSet(); line?

Yes.

For unmodifiable sets in Java 9 , use Set.of.

Set< Integer > integers = Set.of( 4 , 7 , 12 ) ;

You asked:

how can I add multiple values at once

You can use Set.of as convenient syntax for adding to an existing set. Call Set#addAll.

Set< Integer > integers = new HashSet<>() ;
integers.addAll( Set.of( 4 , 7 , 12 ) ) ;  

That use of Set.of( 4 , 7 , 12 ) is a modern alternative to Arrays.asList( 4 , 7 , 12 ) seen in other Answers on this page.

When you are done modifying a set, you may wish to convert it into an unmodifiable set. For example, this approach is usually wise when handing off a set between methods. In Java 10 , call Set#copyOf.

Set< Integer > integersUnmodifiable = Set.copyOf( integers ) ;

See similar code run live at IdeOne.com.

CodePudding user response:

Sure, if you had the numbers in another collection, you could add them all at once.

Documentation link.

But then the question is whether or not it's worth making the other collection in order to use it to make this collection. If you're making an array from the numbers, and using that to make an ArrayList, and using that to populate the HashMap, it's starting to seem a little indirect for my taste.

It rather depends on the situation. Is "adding 3 constant numbers" a likely scenario?

CodePudding user response:

Initializing with values:

  Set<Integer> set1 = new HashSet<>(Arrays.asList(1,2,3,4,5,6));

Adding multiple values:

Collections.addAll(set1, 1,2,3,4,5,6);

reference.

  •  Tags:  
  • java
  • Related