Only objects that pass the test in the given predicate can be added to the set. Trying to add an invalid object results in an IllegalArgumentException. It is important not to use the original set after invoking this method, as it is a backdoor for adding invalid objects.
A Collection that excludes duplicate elements is referred to as a Set. It simulates the abstraction of a set in mathematics. A set is a group of items where no item appears certified devops generalist more than once. Sets implement every method in the Collection interface, but they do so in a way that makes sure no element appears more than once in the set.
In the above example, we have used the Guava library to get the difference between two sets. In order to run this program, you need to implement Guava Library by adding it in your dependency. It actually returns a delta providing the list of elements added and remove. You can make a union using .addAll(), and an intersection using .retainAll(), of the two sets and use .removeIf(), to remove the intersection from the union. This will work but I think it would be a nice feature to have the set operations like union , difference built in java.
Returns a synchronized sorted set backed by the given sorted set. Collections class uses static methods for computations, also known as utility methods that are used to operate on the collection. The list provides positional access of the elements in the collection. But, no new methods are defined inside Set interface, so we have to use Collection interface methods only with Set subclasses . If you find this Java interview question interesting and my explanation useful then please share it with your friends and colleagues.
Suppose you want to know which words in the argument list occur only once and which occur more than once, but you do not want any duplicates printed out repeatedly. This effect can be achieved by generating two sets — one containing every word in the argument list and the other containing only the duplicates. The words that occur only once are the set difference of these two sets, which we know how to compute. The implementation type of the Set in the preceding example is HashSet, which makes no guarantees as to the order of the elements in the Set. If you want the program to print the word list in alphabetical order, merely change the Set’s implementation type from HashSet to TreeSet. Making this trivial one-line change causes the command line in the previous example to generate the following output.
List is one of the sub-interface in the collection and is also similar to Python Lists with some differences and used for ordered elements or objects in sorted form. A list’s elements are accessible with the help of its elements’ index or position. The most commonly used list classes on the list interfaces are Vector, Stack, LinkedList, ArrayList, and CopyOnWriteArrayList.