Python Java Functionality Equivalent & # 8594; set (string)

I want to emulate Python functions in Java. In Python, if I want unique characters in a string, I can only do

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?

+3
source share
1 answer
String str = "i am a string";
System.out.println(new HashSet<String>(Arrays.asList(str.split(""))));

EDIT: for those who object that they are not completely equivalent, since str.split will contain an empty string in the set, we can make this 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.

+7
source

Source: https://habr.com/ru/post/1716695/


All Articles