Merge pull request #7059 from codehunter34/BAEL-2969

Bael 2969
This commit is contained in:
rpvilao 2019-06-10 18:26:31 +02:00 committed by GitHub
commit e99e2389dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 83 additions and 1 deletions

View File

@ -0,0 +1,13 @@
package com.baeldung.set;
import java.util.Set;
public class CopySets {
// Using Java 10
public static <T> Set<T> copyBySetCopyOf(Set<T> original) {
Set<T> copy = Set.copyOf(original);
return copy;
}
}

View File

@ -24,10 +24,20 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.3</commons-collections4.version>
<guava.version>27.1-jre</guava.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,59 @@
package com.baeldung.set;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang.SerializationUtils;
import com.google.gson.Gson;
public class CopySets {
// Copy Constructor
public static <T> Set<T> copyByConstructor(Set<T> original) {
Set<T> copy = new HashSet<>(original);
return copy;
}
// Set.addAll
public static <T> Set<T> copyBySetAddAll(Set<T> original) {
Set<T> copy = new HashSet<>();
copy.addAll(original);
return copy;
}
// Set.clone
public static <T> Set<T> copyBySetClone(HashSet<T> original) {
Set<T> copy = (Set<T>) original.clone();
return copy;
}
// JSON
public static <T> Set<T> copyByJson(Set<T> original) {
Gson gson = new Gson();
String jsonStr = gson.toJson(original);
Set<T> copy = gson.fromJson(jsonStr, Set.class);
return copy;
}
// Apache Commons Lang
public static <T extends Serializable> Set<T> copyByApacheCommonsLang(Set<T> original) {
Set<T> copy = new HashSet<>();
for (T item : original) {
copy.add((T) SerializationUtils.clone(item));
}
return copy;
}
// Collectors.toSet
public static <T extends Serializable> Set<T> copyByCollectorsToSet(Set<T> original) {
Set<T> copy = original.stream()
.collect(Collectors.toSet());
return copy;
}
}