Is there a Java 8 equivalent for grail sorting method?

I am trying to split a list into a list of lists. In groovy, I can easily do this:

def letters = 'a'..'g'

assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

      

Is there an equivalent in Java 8? I've looked at Collectors, but it seems a bit tricky. I just want to group the items in a list at x.

+3


source to share


4 answers


You can look into the Partition API for Guava Lists:

public static <T> java.util.List<java.util.List<T>> partition(java.util.List<T> list, int size)

      



Returns consecutive sublists of the list, each of which is the same size (the last list may be smaller).

+2


source


How about this?

char start = 'a';
char last = 'g';
int n = 3;

List<Character> letters = IntStream.rangeClosed(start, last)
                                   .mapToObj(it -> (char) it)
                                   .collect(toList());

List<List<Character>> result = IntStream.range(0, (letters.size() + n - 1) / n)
               .map(i -> i * n)
               .mapToObj(i -> letters.subList(i, Math.min(i + n, letters.size())))
               .collect(toList());

      



OR

List<List<Character>> result = IntStream.range(0, letters.size()).boxed().
          collect(collectingAndThen(
               groupingBy(i -> i / n, mapping(letters::get, toList())),
               map -> new ArrayList<>(map.values())
          ));

      

+2


source


This was discussed earlier, but I can't find it right now, so this is a neat way to do it:

private static <T> Collector<T, ?, List<List<T>>> partitioning(int size) {
    class Acc {
        int count = 0;

        List<List<T>> list = new ArrayList<>();

        void add(T elem) {
            int index = count++ / size;
            if (index == list.size()) {
                list.add(new ArrayList<>());
            }
            list.get(index).add(elem);
        }

        Acc merge(Acc right) {

            List<T> lastLeftList = list.get(list.size() - 1);
            List<T> firstRightList = right.list.get(0);
            int lastLeftSize = lastLeftList.size();
            int firstRightSize = firstRightList.size();

            // they are both size, simply addAll will work
            if (lastLeftSize + firstRightSize == 2 * size) {
                System.out.println("Perfect!");
                list.addAll(right.list);
                return this;
            }

            // last and first from each chunk are merged "perfectly"
            if (lastLeftSize + firstRightSize == size) {
                System.out.println("Almost perfect");
                int x = 0;
                while (x < firstRightSize) {
                    lastLeftList.add(firstRightList.remove(x));
                    --firstRightSize;
                }
                right.list.remove(0);
                list.addAll(right.list);
                return this;
            }

            right.list.stream().flatMap(List::stream).forEach(this::add);
            return this;
        }

        public List<List<T>> finisher() {
            return list;
        }

    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}

      

And usage:

List<List<Integer>> list = Arrays.asList(1, 3, 4, 5, 9, 8, 7)
            .stream()
            .parallel()
            .collect(partitioning(3));

      

The point is, this is a good job for parallel streams through combiner

. Also, less code doesn't mean better or more productive solutions.

+1


source


Try my library AbacusUtil

CharStream.rangeClosed('a', 'g').split(3).println();
// print out: [[a, b, c], [d, e, f], [g]]

      

0


source







All Articles