BAEL-2969: Copying Sets in Java

This commit is contained in:
codehunter34 2019-06-07 15:01:42 -04:00
parent 858927c985
commit d69a81e25c
2 changed files with 43 additions and 43 deletions

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-set</artifactId>

View File

@ -11,54 +11,55 @@ 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;
}
// 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.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;
}
// 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);
// 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;
}
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;
}
// 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());
// Collectors.toSet
public static <T extends Serializable> Set<T> copyByCollectorsToSet(Set<T> original) {
Set<T> copy = original.stream()
.collect(Collectors.toSet());
return copy;
}
return copy;
}
// Using Java 10
public static <T> Set<T> copyBySetCopyOf(Set<T> original) {
Set<T> copy = Set.copyOf(original);
return copy;
}
// Using Java 10
public static <T> Set<T> copyBySetCopyOf(Set<T> original) {
Set<T> copy = Set.copyOf(original);
return copy;
}
}