How to convert a hierarchical collection to a flat collection by Java 7 vs Java 8 ?

Consider you have a Hierarchical collection as List<List<String>> and you want to convert it into a flat collection like List<String>.

convert-collection

First consider the same by Java 7

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FlatCollectionByJava7 {

  /**
   * Convert into flat list by Java 7
   * @param collection
   * @return
   */
  public static List flatCollectionJava7(List<List<String>> collection) {
	List flatList = new ArrayList<>();
	for (List list : collection) {
		for (String value : list) {
			flatList.add(value);
		}
	}
	return flatList;
  }


  public static void main(String[] args) {
	List aList = Arrays.asList("Ninja","Panda","Java7");
	List bList = Arrays.asList("Ninja","CC","Java8","Tuturself");
	List<List<String>> hierarchicalList = new ArrayList<>();
	hierarchicalList.add(aList);
	hierarchicalList.add(bList);

	System.out.println("Convert to Flat List By Java 7");
	System.out.println("-------------------------------");
	System.out.println(flatCollectionJava7(hierarchicalList));
  }
}

The O/P of the program is:

Convert to Flat List By Java 7
-------------------------------
[Ninja, Panda, Java7, Ninja, CC, Java8, Tuturself]

Now let us use Java 8 to implement the same. Here we will use flatMap of Java 8

import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FlatMapJava8 {

  /**
   * Convert into flat list by Java 8
   * @param collection
   * @return
   */
  public static List flatCollectionJava8(List<List<String>> collection) {
	return collection.stream() // Convert collection to Stream
			.flatMap(value -> value.stream()) // Replace list with stream
			.collect(toList()); // Collect results to a new list
  }  

  public static void main(String[] args) {
	List aList = Arrays.asList("Ninja","Panda","Java7");
	List bList = Arrays.asList("Ninja","CC","Java8","Tuturself");
	List<List<String>> hierarchicalList = new ArrayList<>();
	hierarchicalList.add(aList);
	hierarchicalList.add(bList);

	System.out.println("Convert to Flat List By Java 8");
	System.out.println("-------------------------------");
	System.out.println(flatCollectionJava8(hierarchicalList));
  }
}

The O/P of the program is:

Convert to Flat List By Java 8
-------------------------------
[Ninja, Panda, Java7, Ninja, CC, Java8, Tuturself]

 

Java-8 12 Stream 12

FOLLOW US ON LinkedIn



Explore Tutu'rself