# Read a line from console in Java

I have to read a line of strings and split it for whitespace:

ArrayList<HashSet<String>> setOfStrings = new ArrayList<HashSet<String>>();
String[] tokens = currentLine.split(" ");
for (int i = 0; i < tokens.length; i++) {
}
}


i have to do this ,and for this reason i need for each tokens a new hashSet

i need to make operations on tokens like

[afaf] -> one hashset in first position inside the arrayList
[bafafa] -> one hashset in second position inside the arrayList
[cssss]
[dggg]
...


with your solution ,to make a unique hashset for the tokens, i can't do separate operations for each tokens.

How can I improve the split of the currentLine and the insertion into the arrayList? As I did it, it's very slow because I first have to split and then iterate on the array of tokens. How can I optimize this operation?

-
Why not a List for the tokens? –  Marco Acierno Jun 9 '14 at 0:04

Is the use of a Set for storing the tokens deliberate? That's because you can only have unique elements in the Set, and the output of the following code snippet will be 1, not 2:

System.out.println( new HashSet<>( Arrays.asList( "a a".split( " " ) ) ).size() );


Also, what you are doing is to store one token into a new List via Arrays.asList(), this is then iterated for elements to be stored into a new HashSet, which is finally added to setOfStrings. May we know what exactly are you trying to do here? I'll attempt to illustrate the output for the following:

Input:

a b c
d e f


Output:

setOfStrings
new HashSet [ "a" ]
new HashSet [ "b" ]
new HashSet [ "c" ]
new HashSet [ "d" ]
new HashSet [ "e" ]
new HashSet [ "f" ]


edit:

After reading your comment, I think what you're looking for is this:

while ((currentLine = bufferedReader.readLine()) != null) {
String[] tokens = currentLine.split(" ");
}


You do not have to iterate through tokens... Alternative suggestion relying on the utility method from the Collections class:

while ((currentLine = bufferedReader.readLine()) != null) {
Set<String> hashSet = new HashSet<>();
Collections.addAll( hashSet, currentLine.split( " " ) );

Do pay attention to its Javadoc: "The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations." :)
If that's the case then you should be looking at adding all your tokens from a line into a single HashSet instance, not to create a HashSet instance per token. –  h.j.k. Jun 9 '14 at 6:53
so for example u suggest to do this setOfStrings.add(new HashSet<String>(Arrays.asList(tokens))); ? is there a way to add the tokens without converting them into an array with this Arrays.asList(tokens)) –  OiRc Jun 9 '14 at 6:58
Just to be sure we're clear on each other definitions, a line "a a" will yield two tokens after split(), and there will only be one unique value a, is that your understanding too? –  h.j.k. Jun 9 '14 at 7:26