fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. List < List < Integer > > listOfLists =
  13. List.of(
  14. List.of( 1 , 2 , 3 ) ,
  15. List.of( 4 , 5 ) ,
  16. List.of( 6 , 7 , 8 )
  17. );
  18. OptionalInt longestLength = listOfLists.stream().mapToInt( List :: size ).max();
  19. int limit = longestLength.orElse( 0 );
  20.  
  21. int initialCapacity = listOfLists.stream().mapToInt( List :: size ).sum();
  22. List < Integer > results = new ArrayList <>( initialCapacity );
  23. for ( int i = 0 ; i < limit ; i++ )
  24. {
  25. for ( List < Integer > listOfIntegers : listOfLists )
  26. {
  27. try
  28. {
  29. Integer integer = listOfIntegers.get( i );
  30. results.add( integer );
  31. }
  32. {
  33. // Do nothing. Swallow exception. We expect to fall out of bounds on shorter lists.
  34. }
  35. }
  36. }
  37.  
  38. System.out.println( "listOfLists = " + listOfLists );
  39. System.out.println( "longestLength = " + longestLength );
  40. System.out.println( "limit = " + limit );
  41. System.out.println( "results = " + results );
  42. }
  43. }
Success #stdin #stdout 0.14s 51244KB
stdin
Standard input is empty
stdout
listOfLists = [[1, 2, 3], [4, 5], [6, 7, 8]]
longestLength = OptionalInt[3]
limit = 3
results = [1, 4, 6, 2, 5, 7, 3, 8]