-3

I can propose few answers myself, but they are very far from being elegant.

Prove me that Java is not that hopeless. Thanks.

ptkvsk
  • 2,096
  • 1
  • 25
  • 47

1 Answers1

3

In Java 8+, you might use a forEach and something like

String str = "Hello";
Set<Character> set = new LinkedHashSet<>();
str.chars().forEach(e -> set.add((char) e));
System.out.println(set);

which outputs

[H, e, l, o]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    Does not seem like a oneliner to me... – ptkvsk Oct 21 '15 at 02:35
  • 2
    It has two advantages over other suggestions, it works and it's easy to understand. Reducing code to one line serves what practical purpose? – Elliott Frisch Oct 21 '15 at 02:37
  • Ability to use it in static member initializer. – ptkvsk Oct 21 '15 at 02:38
  • You should prefer the collect approach (which a one-liner btw), than the for-each one. It suffices that someone turns the stream in parallel so that you run into concurrency issues. – Alexis C. Oct 21 '15 at 08:27
  • I think, if you decide to use a tool (like streams), you should do it the intended way. Using `forEach` to mutate an existing collection should be the last resort, if the existing operations don’t work. This is not appopriate here as there is a canonical solution: `str.chars().mapToObj(i->(char)i).collect(Collectors.toSet())` – Holger Oct 21 '15 at 10:33
  • If you want to control the type of the `Set`, using a custom collector becomes more concise:
 `.chars().collect(LinkedHashSet::new, (s,i)->s.add((char)i), Set::addAll)` – Holger Oct 21 '15 at 10:39