BAEL-2969: Copying Sets in Java

This commit is contained in:
codehunter34 2019-06-07 14:55:13 -04:00
parent a0282482bc
commit 858927c985
1 changed files with 41 additions and 51 deletions

View File

@ -2,7 +2,6 @@ package com.baeldung.set;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@ -12,63 +11,54 @@ import com.google.gson.Gson;
public class CopySets {
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;
}
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;
}
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;
}
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;
}
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;
}
public static <T> void copyByStreamsAPI(Set<T> original) {
Set<T> copy1 = 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());
// Skip the first element
Set<T> copy2 = original.stream()
.skip(1)
.collect(Collectors.toSet());
return copy;
}
// Filter by comparing the types and attributes
Set<T> copy3 = original.stream()
.filter(f -> f.getClass()
.equals(Integer.class))
.collect(Collectors.toSet());
// Null check in case of expecting null values
Set<T> copy4 = original.stream()
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
public static <T> Set<T> copyByJava8(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;
}
}