Home > Software design >  How can i split ArrayList<String> to ArrayList<Character> in java?
How can i split ArrayList<String> to ArrayList<Character> in java?

Time:05-20

I have ArrayList of type String like ArrayList words = new ArrayList<>(Arrays.asList("hello","Monjed","Nidal")); and i want to split this arraylist to type character like "h","e","l","l"....

CodePudding user response:

You can use streams to do this. Your question is a little unclear, do you want a list of char lists or a single list with all the chars in it?

List of lists:

words.stream().map(word -> Arrays.asList(word.toCharArray())).collect(Collectors.toList());

Single list of chars:

words.stream().flatMap(word -> Stream.of(word.toCharArray())).collect(Collectors.toList());

CodePudding user response:

You can do it by using streams.

List<String> stringList = Arrays.asList("Hello", "World");
List<Character> charList = new ArrayList<>();
stringList.forEach(item ->
   charList.addAll(item.chars().mapToObj(e -> (char) e).toList())
);

Output will be: [H, e, l, l, o, W, o, r, l, d]

  • Related