Skip to content

Commit

Permalink
Add support for Sets#newHashSet(Iterable)
Browse files Browse the repository at this point in the history
  • Loading branch information
jkschneider committed Jun 16, 2021
1 parent aae345f commit 5476c21
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import java.util.stream.Collectors;

Expand Down Expand Up @@ -52,13 +54,21 @@ protected TreeVisitor<?, ExecutionContext> getVisitor() {
.imports("java.util.HashSet")
.build();

private final JavaTemplate newHashSetIterable = template("new HashSet<>(#{any(java.lang.Iterable)})")
.imports("java.util.HashSet")
.build();

@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) {
if (NEW_HASH_SET.matches(method)) {
maybeRemoveImport("com.google.common.collect.Sets");
maybeAddImport("java.util.HashSet");
if(method.getArguments().isEmpty()) {
return method.withTemplate(newHashSet, method.getCoordinates().replace());
} else if(method.getArguments().size() == 1 && TypeUtils.isAssignableTo(JavaType.Class.build("java.lang.Iterable"),
method.getArguments().get(0).getType())) {
return method.withTemplate(newHashSetIterable, method.getCoordinates().replace(),
method.getArguments().get(0));
} else {
maybeAddImport("java.util.Arrays");
JavaTemplate newHashSetVarargs = template("new HashSet<>(Arrays.asList(" + method.getArguments().stream().map(a -> "#{any()}").collect(Collectors.joining(",")) + "))")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,33 @@ class NoGuavaSetsNewHashSetTest: JavaRecipeTest {
"""
)

@Test
fun replaceWithNewHashSetIterable() = assertChanged(
before = """
import com.google.common.collect.*;
import java.util.Collections;
import java.util.List;
import java.util.Set;
class Test {
List<Integer> l = Collections.emptyList();
Set<Integer> cardinalsWorldSeries = Sets.newHashSet(l);
}
""",
after = """
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Test {
List<Integer> l = Collections.emptyList();
Set<Integer> cardinalsWorldSeries = new HashSet<>(l);
}
"""
)

@Test
fun replaceWithNewHashSetVarargs() = assertChanged(
before = """
Expand Down

0 comments on commit 5476c21

Please sign in to comment.