Tuesday, November 1, 2022

Question 20 : Flattening Nested Collections using java 8

Example of a Nested Collection

List<List<String>> nestedList = asList(
  asList("one:one"), 
  asList("two:one", "two:two", "two:three"), 
  asList("three:one", "three:two", "three:three", "three:four"));

 Flattening the List With flatMap

 import java.util.*;

import java.util.Collections;
import java.util.stream.Collectors;

public class flattenListrMain {
 
 public static <T> List<T>  flattenListOfListsStream(List<List<T>> list) {
    return list.stream()
      .flatMap(Collection::stream)
      .collect(Collectors.toList());    
 }
 
 public static void main(String[] args) {
  
      List<List<String>> nestedList = Arrays.asList(
      Arrays.asList("one:two"), 
      Arrays.asList("three:four", "five:six", "saven:nine"), 
      Arrays.asList("three:one", "three:two", "three:three", "three:four"));
    
      List<String> ls = StringAllUniqueCharMain.flattenListOfListsStream(nestedList);
      System.out.println("flattenList "+ ls);
 }
}

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS