Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of a Python functionality -> set(string)

Tags:

java

python

set

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?

like image 655
Chantz Avatar asked Sep 02 '09 14:09

Chantz


1 Answers

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.

like image 148
Yishai Avatar answered Sep 20 '22 02:09

Yishai