Reputation: 197
So I am currently having a problem understanding how to access a set, is that even allowed? So I understand my set of names contains a set of Character objects. I also understand that my toString()
method call converts these Character objects into a String, but not a conventional string -- which is why I have [s,a]
rather than [sa].
So my question is, is if there is a way to make me have a list of individual strings. So I want my list to be = [s, a]
rather than [ [s,a] ].
Is this even possible? I apologize if this makes no sense; nevertheless, if you do understand my fumbled explanation thank you for your time and help. If you need for me to explain more, I will.
//this all works
Set<Character> names = find(prefix).getRollCall().keySet();
//[s,a]
String lists = names.toString();
//[s,a]
List<String> sloop = Arrays.asList(lists);
//[[s,a]]
Upvotes: 0
Views: 56
Reputation: 27946
Let me explain what's happening in your code, in case you aren't clear:
String lists = names.toString();
This calls the standard toString
method for a collection which converts your set to an ordinary (conventional) string in a standard format (i.e. comma delimited, in brackets). There's nothing special about the string that is created: "[s, a]".
List<String> sloop = Arrays.asList(lists);
The asList
method takes one or more arguments and converts them into a list. Because you've given it only a single argument lists
it creates a list with a single string element: ("[s, a]")
Then, later, I suspect you are doing something like:
System.out.println(sloop);
This again calls the standard toString
method for a collection (in this case the List
sloop) and again creates a comma delimited, bracket enclosed standard string: "[[s, a]]"
So, most of that is probably not what you want. Your lists
variable isn't a List
, it's a String
which I assume isn't what you want.
If you are just looking to convert your set of character to a list of strings, then this is pretty trivial in Java 8:
List<String> lists = names.stream().map(Character::toString).collect(Collectors.toList());
Upvotes: 1
Reputation: 310840
Don't use toString()
at all. Iterate over the elements of the Set
and build up whatever string you like.
Set<Character> names = find(prefix).getRollCall().keySet();
for (Character c : names)
{
// whatever you like
}
Upvotes: 2
Reputation: 37645
If you want to convert a Set<Character>
to a List<Character>
you can do
List<Character> list = new ArrayList<Character>(set);
If you want to convert a Set<Character>
to a List<String>
you can do
List<String> list = new ArrayList<String>();
for (char c : set)
list.add("" + c);
Upvotes: 3