I have the following input for the array list :
[item II, model IX, brand XX]
the desired output is as follows:
[II, IX, XX]
I try the following:
int size = names.size();
for(int i = 0; i < size; i )
{
System.out.println(names);
String d=Arrays.toString(names.get(i).split("\\s "));
System.out.println(d);}
the above code will return a string as follows, I am stuck on how to index the string, in this case, to take the second element in a simple way.
[item, II]
[model, IX]
[brand, XX]
CodePudding user response:
The String.split() method returns a String array. For example, "item II".split("\\s ")
would return a String array like: {"item", "II"}. So, you can just call for the second item in the array returned by the split method.
String d = names.get(i).split("\\s ")[1];
CodePudding user response:
Using streams:
package parsestring;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ParseOnSpace {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("item II", "model IX", "brand XX"));
List<String> values = names.stream()
.map(name -> name.split(" ")[1])
.collect(Collectors.toList());
System.out.println(values);
}
}
CodePudding user response:
I think this is what you want. After the split, which returns an array, you can index the second item.
List<String> names = new ArrayList<String>();
names.add("item II");
names.add("model IX");
names.add("brand XX");
List<String> secondNames = new ArrayList<String>();
for (String name : names) {
String second = name.split("\\s ")[1]; // get second item
secondNames.add(second);
}