@@ -48,41 +48,43 @@ public String getDescription() {
4848
4949 @ Override
5050 public TreeVisitor <?, ExecutionContext > getVisitor () {
51- return Preconditions .check (Preconditions .and (new UsesJavaVersion <>(10 ),
52- new UsesMethod <>(NEW_HASH_MAP )), new UseMapOfVisitor ());
53- }
51+ return Preconditions .check (
52+ Preconditions .and (
53+ new UsesJavaVersion <>(10 ),
54+ new UsesMethod <>(NEW_HASH_MAP )),
55+ new JavaVisitor <ExecutionContext >() {
56+ @ Override
57+ public J visitNewClass (J .NewClass newClass , ExecutionContext ctx ) {
58+ J .NewClass n = (J .NewClass ) super .visitNewClass (newClass , ctx );
59+ J .Block body = n .getBody ();
60+ if (NEW_HASH_MAP .matches (n ) && body != null && body .getStatements ().size () == 1 ) {
61+ Statement statement = body .getStatements ().get (0 );
62+ if (statement instanceof J .Block ) {
63+ List <Expression > args = new ArrayList <>();
64+ StringJoiner mapOf = new StringJoiner (", " , "Map.of(" , ")" );
65+ for (Statement stat : ((J .Block ) statement ).getStatements ()) {
66+ if (!(stat instanceof J .MethodInvocation ) || !MAP_PUT .matches ((Expression ) stat )) {
67+ return n ;
68+ }
69+ J .MethodInvocation put = (J .MethodInvocation ) stat ;
70+ args .addAll (put .getArguments ());
71+ mapOf .add ("#{any()}" );
72+ mapOf .add ("#{any()}" );
73+ }
5474
55- private static class UseMapOfVisitor extends JavaVisitor <ExecutionContext > {
56- @ Override
57- public J visitNewClass (J .NewClass newClass , ExecutionContext ctx ) {
58- J .NewClass n = (J .NewClass ) super .visitNewClass (newClass , ctx );
59- J .Block body = n .getBody ();
60- if (NEW_HASH_MAP .matches (n ) && body != null && body .getStatements ().size () == 1 ) {
61- Statement statement = body .getStatements ().get (0 );
62- if (statement instanceof J .Block ) {
63- List <Expression > args = new ArrayList <>();
64- StringJoiner mapOf = new StringJoiner (", " , "Map.of(" , ")" );
65- for (Statement stat : ((J .Block ) statement ).getStatements ()) {
66- if (!(stat instanceof J .MethodInvocation ) || !MAP_PUT .matches ((Expression ) stat )) {
67- return n ;
75+ maybeRemoveImport ("java.util.HashMap" );
76+ maybeAddImport ("java.util.Map" );
77+ return JavaTemplate .builder (mapOf .toString ())
78+ .contextSensitive ()
79+ .imports ("java.util.Map" )
80+ .build ()
81+ .apply (updateCursor (n ), n .getCoordinates ().replace (), args .toArray ());
82+ }
6883 }
69- J .MethodInvocation put = (J .MethodInvocation ) stat ;
70- args .addAll (put .getArguments ());
71- mapOf .add ("#{any()}" );
72- mapOf .add ("#{any()}" );
73- }
74-
75- maybeRemoveImport ("java.util.HashMap" );
76- maybeAddImport ("java.util.Map" );
77- return JavaTemplate .builder (mapOf .toString ())
78- .contextSensitive ()
79- .imports ("java.util.Map" )
80- .build ()
81- .apply (updateCursor (n ), n .getCoordinates ().replace (), args .toArray ());
82- }
83- }
8484
85- return n ;
86- }
85+ return n ;
86+ }
87+ });
8788 }
89+
8890}
0 commit comments