Reputation: 31
How would I convert a list of list of strings into a single comma separated list (flatten the lists in one)? Eg:
[[[B1, TMC, Streampix], [HSD1, Streampix - HSD], [CDV1, CDV2]]]
into
[B1, TMC, Streampix], [HSD1, Streampix - HSD], [CDV1, CDV2]
Upvotes: 2
Views: 1395
Reputation: 21975
It becomes really easy using java-8 streams.
Stream over each list, convert it to a string separated by commas and then collect them all in a big list.
List<String> newList = list.stream()
.map(x -> x.stream().collect(Collectors.joining(",")))
.collect(Collectors.toList());
newList.forEach(System.out::println);
B1,TMC,Streampix
HSD1,Streampix - HSD
CDV1,CDV2
Upvotes: 2
Reputation: 23815
Use StringUtils.join() method if you have Apache Commons Lang lib
suppose list has following element
List list = [[["B1", "TMC", "Streampix"], ["HSD1", "Streampix - HSD"], ["CDV1", "CDV2"]]]
then :
String strList = StringUtils.join(list,',');
System.out.println(strList);
output :
[[B1, TMC, Streampix], [HSD1, Streampix - HSD], [CDV1, CDV2]]
for the reference see link How to convert a List<String> list to csv string
Hope this will help you...:)
Upvotes: 1
Reputation: 425
Do you mean this:
//inputList is your List of List of String
List<String> retval = new ArrayList<>();
for(List<String> l : inputList){
retval.add(l.toString());
}
then the retval = [B1, TMC, Streampix], [HSD1, Streampix - HSD], [CDV1, CDV2]
Upvotes: 0
Reputation: 777
This is actually really simple.
You can actually create an arraylist of arraylists! Then print that out with a loop and it will be in the format you want automatically
Here is an example I think may help you.
ArrayList<ArrayList> list = new ArrayList();//create a list of lists
ArrayList<String> test = new ArrayList();//sample data
ArrayList<String> test2 = new ArrayList();//sample data
test.add("Test");//add sample data to list
test.add("Test");
test.add("Test");
test2.add("Test");
test2.add("Test");
test2.add("Test");
list.add(test);//ad sample lists to main list
list.add(test2);
for (int i = 0; i < list.size(); i++)//this is what you want for your list
System.out.println(list.get(i));
This has an output of
[Test, Test, Test] [Test, Test, Test] instead of [[Test, Test, Test],[Test, Test, Test]]
Upvotes: 0