Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to combine two string sets in java?

Tags:

java

set

I need to combine two string sets while filtering out redundant information, this is the solution I came up with, is there a better way that anyone can suggest? Perhaps something built in that I overlooked? Didn't have any luck with google.

Set<String> oldStringSet = getOldStringSet(); Set<String> newStringSet = getNewStringSet();  for(String currentString : oldStringSet) {     if (!newStringSet.contains(currentString))     {         newStringSet.add(currentString);     } } 
like image 972
FooBar Avatar asked Jan 30 '12 10:01

FooBar


People also ask

How can you combine two sets into one?

Press Ctrl+click to highlight two sets, and right-click either set to display a shortcut menu that allows you to Create Combined Set. Drag the pill for the set you want to combine to the left of the other set on the Rows shelf, and select Create Combined Set.

How do you combine strings in Java?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.

Can you add a set to a set Java?

The java. util. Set. addAll(Collection C) method is used to append all of the elements from the mentioned collection to the existing set.


2 Answers

Since a Set does not contain duplicate entries, you can therefore combine the two by:

newStringSet.addAll(oldStringSet); 

It does not matter if you add things twice, the set will only contain the element once... e.g it's no need to check using contains method.

like image 178
dacwe Avatar answered Sep 23 '22 08:09

dacwe


You can do it using this one-liner

Set<String> combined = Stream.concat(newStringSet.stream(), oldStringSet.stream())         .collect(Collectors.toSet()); 

With a static import it looks even nicer

Set<String> combined = concat(newStringSet.stream(), oldStringSet.stream())         .collect(toSet()); 

Another way is to use flatMap method:

Set<String> combined = Stream.of(newStringSet, oldStringSet).flatMap(Set::stream)         .collect(toSet()); 

Also any collection could easily be combined with a single element

Set<String> combined = concat(newStringSet.stream(), Stream.of(singleValue))         .collect(toSet()); 
like image 36
ytterrr Avatar answered Sep 23 '22 08:09

ytterrr