Advertisement
spkenny

all sublists of a list

Feb 11th, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1.     public static <T extends Comparable<T>> List<List<T>> subsets(List<T> list)
  2.     {
  3.         List<List<T>> returnValue;
  4.         if ( list.isEmpty() )
  5.         {
  6.             List<List<T>> lists =  new ArrayList<List<T>>();
  7.             lists.add(list);
  8.             returnValue = lists;
  9.            
  10.         } else if ( list.size() == 1 )
  11.         {
  12.             List<List<T>> lists =  new ArrayList<List<T>>();
  13.             lists.add(list);
  14.             lists.add(new ArrayList<T>());
  15.             returnValue = lists;
  16.         }
  17.         else
  18.         {
  19.             List<T> firstElement = list.subList(0,1);
  20.             List<T> rest = list.subList( 1, list.size() );
  21.             returnValue = cartesian(subsets(firstElement), subsets(rest));
  22.            
  23.         }
  24.        
  25.         return returnValue;
  26.     }
  27.    
  28.     public static  <T extends Comparable<T>>  List<List<T>> cartesian(List<List<T>> left, List<List<T>> right)
  29.     {
  30.         List<List<T>> returnValue = new ArrayList<>();
  31.         if (left != null && right != null)
  32.         {
  33.             for ( List<T> leftElement : left )
  34.             {
  35.                 for ( List<T> rightElement : right )
  36.                 {
  37.                     returnValue.add(Stream.concat( leftElement.stream(), rightElement.stream() ).collect(Collectors.toList()));
  38.                 }
  39.             }
  40.         }
  41.         return returnValue;
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement