commit
e99e2389dd
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue