I want to mimic a Python functionality in Java. In Python if I want unique characters in a string I can do just,
text = "i am a string"
print set(text) # o/p is set(['a', ' ', 'g', 'i', 'm', 'n', 's', 'r', 't'])
How can I do this in Java trivially or directly?
String str = "i am a string";
System.out.println(new HashSet<String>(Arrays.asList(str.split(""))));
EDIT: For those who object that they aren't exactly equivalent because str.split will include an empty string in the set, we can do it even more verbose:
String str = "i am a string";
Set<String> set = new HashSet<String>(Arrays.asList(str.split("")));
set.remove("");
System.out.println(set);
But of course it depends on what you need to accomplish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With