2

Is there a way to refactor this in IntelliJ (or even with Eclipse), to transform the first script to the second one :

Set initialization before Java 9 :

Set<String> values = new HashSet<>();
values.add("a");
values.add("b");

Set initialization starting from Java 9 (creates an immutable set) :

Set<String> values = Set.of("a", "b");
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
Guillaume Husta
  • 4,049
  • 33
  • 40
  • 1
    You might have been happier to have found [this Q&A](https://stackoverflow.com/questions/2041778/how-to-initialize-hashset-values-by-construction) before the current code implementation you've shared. The standard operations do not provide an option to refactor such code at present. On the contrary, I don't even see the usefulness in performing such task for a user, given that the characteristics of the two `Set`(`new HashSet` Vs `Set.of`) differ significantly. – Naman Dec 03 '19 at 17:07
  • 2
    Do note a possibility of `Set values = new HashSet<>(); values.add("a"); values.add("b"); System.out.println(values);//consumed values.add("c"); //modified System.out.println(values);//consumed`, how would you expect this to be refactored? – Naman Dec 03 '19 at 17:11
  • I understand that there are differences between both codes (modifiable vs unmodifiable). But I think that by laziness, some developers won't bother with wrapping the Set with `Collections.unmodifiableSet()` – Guillaume Husta Dec 03 '19 at 19:59
  • I wish I could use the same syntax available in Python (_set / frozenset_), like described in [Sets in Python](https://www.geeksforgeeks.org/sets-in-python/) – Guillaume Husta Dec 03 '19 at 20:17

1 Answers1

1

The refactoring option may not be available in all the cases (the source set should be unmodifiable).

However IntelliJ has inspections that may be more suitable to detect such a case.

See under Java > Java language level migration aids > Java 9 : Immutable collection creation can be replaced with collection factory call :

This inspection helps to convert unmodifiable collections created before Java 9 to new collection factory methods like List.of or Set.of. Also since Java 10 the conversion to List.copyOf, etc. could be suggested.

Note that Java 9 collection factory methods do not accept null values. Also set elements and map keys are required to be different. It's not always possible to statically check whether original elements are different and not null. Using the checkbox you may enforce the inspection to warn only if original elements are compile-time constants, so the conversion is guaranteed to be correct.

This inspection is available since Java 9 only.
New in 2017.2

This inspection can be tested with this code :

Set<String> stringSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));
Guillaume Husta
  • 4,049
  • 33
  • 40