Before you doing anything make sure you've read and understood the discussion here: Java benchmarking - why is the second loop faster?

I would expect addAll to be faster in some situations as it has more information to work with.

For example on an ArrayList addAll can make sure it allocates enough space to add every single element in one step, rather than having to reallocate multiple times if adding large numbers of elements.

It would certainly not be slower as even a naive implementation of it would just do what you do, loop through adding the items.

Answer from Tim B on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › set-addall-method-in-java-with-examples
Set addAll() Method in Java - GeeksforGeeks
July 11, 2025 - In Java, the addAll() method of the Set class is used to add all the elements of a specified collection to the current collection.
🌐
Medium
medium.com › @AlexanderObregon › javas-set-addall-method-explained-78ad24f2fead
Java's Set.addAll() Method Explained
December 12, 2024 - The addAll() method is part of the Set interface in Java, which is implemented by classes like HashSet, TreeSet, and LinkedHashSet. This method accepts a single argument: a collection of elements to add.
🌐
Codecademy
codecademy.com › docs › java › set › .addall()
Java | Set | .addAll() | Codecademy
June 1, 2024 - The .addAll() method is declared in the Set interface and is implemented in the HashSet class. It is used to add all of the elements in the specified collection to this set if they’re not already present.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Set.html
Set (Java Platform SE 8 )
2 weeks ago - Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets.
Top answer
1 of 6
10

Copy the cities set (to say, citiesCopy), and then call citiesCopy.retainAll(anotherCitiesSet) - the resulting set in citiesCopy will contain the intersection of the two sets, thus allowing you to easily see which cities are duplicated, if any.

Alternatively, loop through the second set and manually add each of the elements, checking the return value from add() each time:

for(java.util.Set<City> c : anotherCitiesSet) {
    if(!cities.add(c)) {
        // c was a duplicate, do something?
    }
}
2 of 6
3

is your city just String (tho it is object) or it is object containing other stuffs?

  • if String, then I guess above answers will work.

  • if it is object containing things like : String name, int population, etc... And you only want to compare String name to remove duplicates, then you can use {HashSet} class and override its (HashCode) and (equals) methods.

because you may have two cities: NYC, and another NYC. containing the same info. but since they are two objects in heap. they will have different HashCode. There say, your HashSet will keep both of them. HashSet checks both HashCode and meaning equals().

The solution is to override both methods:

class City{
  String name; //if you only care city name
  ....
  ....
  public boolean equals(Object myCity){  // override equals(). only look at the name.
    City city2 = (City) myCity;
    return this.getName().equals(city2.getName());  //String itself has a .equal() to compare
  }

  public int HashCode(){  // override HashCode(). 
    return name.hashCode();  //also String itself has a .hashCode() to check equality
  }

  public String getName(){
    return name;
  }

...
...
}
Top answer
1 of 2
2

addAll basically iterates over the collection it's given and calls add on every method. Here's the way OpenJDK8 implements it:

public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    for (E e : c)
        if (add(e))
            modified = true;
    return modified;
}

But as a general rule of thumb, you shouldn't try to invent the wheel unless you're absolutely sure you can invent a better one.

2 of 2
2

Your question is incomplete. Let’s complete it with the actual alternatives.

First, you have a method which populates a provided Set:

void getSomedata(String param, Set<String> uniqueSet)

which has to be used like

Set<String> uniqueSet = new HashSet<String>();
getSomedata(param1, uniqueSet);
getSomedata(param2, uniqueSet);

The alternative is to have a method which returns a new Set:

Set<String> getSomedata(String param)

which you can use like

Set<String> uniqueSet = getSomedata(param1);
uniqueSet.addAll( getSomedata(param2) );

in this case, you are ignoring how the method getSomedata will create and populate the Set that it will return. Obviously, unless it creates a custom Set implementation projecting source data, it has to create a Set and populate it with elements before returning it.

In other words, it doesn’t matter, how addAll is implemented, at the time you are going to invoke it, this solution has already performed the same work as the other alternative, as it already has added all elements to a Set. So, even if addAll of a particular Set implementation has optimizations, it’s work adds to the already performed work of individually adding all elements to a Set.


Still, the rule that you shouldn’t worry about performance unless there is a real performance problem applies. The involved I/O might outweigh it all. Or the unpredictability of the effects of hotspot optimization and memory management might change it all. If you think, getSomedate returning a new Set is cleaner (that would be reasonable), use it.


As an addendum, I simplified a bit. A HashSet is O(1) only in theory, but will perform different when there are hash collisions and in the case TreeSets are used, which have O(log n) time complexity, the different size of the sets has an effect, thus the alternatives, operating on sets of different size, are not exactly comparable, depending on which Set implementations are used and other surrounding context. But the tendency is still the same, especially as in most cases, there are no optimized addAll implementations (EnumSet might be the only exception).

🌐
Medium
medium.com › @AlexanderObregon › javas-collections-addall-explained-fbed9a316bb2
Java's Collections.addAll() Explained
September 25, 2024 - Sets are collections that automatically handle duplicates, and the Collections.addAll() method is perfectly suited for quickly populating sets while avoiding duplicates. Consider the case of a university system that needs to track the unique courses that students are enrolled in, even though students may enroll in multiple overlapping courses. import java.util.Collections; import java.util.HashSet; import java.util.Set; public class UniversityCourses { public static void main(String[] args) { Set<String> courses = new HashSet<>(); Collections.addAll(courses, "Mathematics", "Computer Science", "Physics", "Chemistry", "Biology"); // Adding more courses Collections.addAll(courses, "Physics", "Astronomy", "Mathematics"); // Duplicate courses will be ignored System.out.println(courses); } }
Find elsewhere
🌐
DEV Community
dev.to › neelakandan_ravi › set-in-java-fb7
Set in Java - DEV Community
March 31, 2025 - The addAll() method appends all the elements of the specified collection to the set. Syntax: boolean addAll(Collection data) import java.io.*; import java.util.*; class SetExample4 { public static void main(String args[]) { Set<Integer> data ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › Set.html
Set (Java Platform SE 7 )
Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Set.html
Set (Java SE 11 & JDK 11 )
January 20, 2026 - Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets.
🌐
CodeGym
codegym.cc › java blog › java collections › java arraylist addall() method
Java ArrayList addAll() method
October 11, 2023 - If you need to add all the elements of one ArrayList() collection to another, you can use the addAll() method of the Java ArrayList class.
🌐
Java Guides
javaguides.net › 2024 › 06 › java-hashset-addall-method.html
Java HashSet addAll() Method
June 12, 2024 - In this example, we'll use the addAll method to add elements from a List to a HashSet. import java.util.HashSet; import java.util.List; import java.util.ArrayList; public class HashSetAddAllExample { public static void main(String[] args) { // Creating a HashSet of Strings HashSet<String> set = new HashSet<>(); set.add("Java"); set.add("Python"); // Creating a List of Strings List<String> list = new ArrayList<>(); list.add("C"); list.add("JavaScript"); // Adding all elements from the List to the HashSet set.addAll(list); // Printing the HashSet System.out.println("HashSet after addAll: " + set); } } Output: HashSet after addAll: [Java, JavaScript, Python, C] In a web application, you might want to merge sets of usernames from different sources.
🌐
Javatpoint
javatpoint.com › java-collections-addall-method
Java Collections addAll() Method with Examples - Javatpoint
Java Collections addAll() Method with Examples on addAll(), asLifoQueue(), checkedCollection(), binarySearch(), CheckedMap(), checkedQueue(), checkedSet(), copy(), emptyEnumeration(), disjoint(), fill(), list(), max(), min(), reverse(), sort(), synchronizedMap() etc.
🌐
Educative
educative.io › answers › what-is-linkedhashsetaddall-in-java
What is LinkedHashSet.addAll in Java?
The addAll method adds all the elements of the passed collection to the LinkedHashSet, if they’re not already present. ... This method takes the collection object, which has to be added in the set as an argument.
🌐
GeeksforGeeks
geeksforgeeks.org › java › sortedset-addall-method-in-java-with-examples
SortedSet addAll() method in Java with Examples - GeeksforGeeks
July 12, 2025 - Set: [4, Geeks, To, TreeSet, Welcome] Set: [4, Geeks, Hello, To, TreeSet, Welcome, World] Program 2 : Appending an ArrayList. ... // Java code to illustrate addAll() import java.io.*; import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set SortedSet<String> st1 = new TreeSet<String>(); // Use add() method to // add elements into the Set st1.add("Welcome"); st1.add("To"); st1.add("Geeks"); st1.add("4"); st1.add("Geeks"); st1.add("Set"); // Displaying the Set System.out.println("Initial Set: " + st1); // An array collection is created ArrayList<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); // Using addAll() method to Append st1.addAll(collect); // Displaying the final Set System.out.println("Final Set: " + st1); } }
🌐
Vultr
docs.vultr.com › java › standard library › java › util › arraylist › addall()
Java ArrayList addAll() - Add Collection Elements
September 27, 2024 - Here, a HashSet is used to ensure no duplicates are added, demonstrating how to handle duplicate elements when using addAll() by employing a set that doesn’t allow duplicates. The addAll() function in Java's ArrayList is indispensable for developers needing to merge collections efficiently.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-list-add-addall-methods
How To Use add() and addAll() Methods for Java List | DigitalOcean
Learn how to use Java List add() and addAll() methods with examples. Understand syntax, performance, and best practices for managing collections.