Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2016 Timo Vesalainen <timo.vesalainen@iki.fi>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.function.Predicate;

public class Main {
    /**
     * Splits list into several sub-lists according to predicate.
     * @param <T>
     * @param list
     * @param predicate
     * @return 
     */
    public static final <T> List<List<T>> split(List<T> list, Predicate<T> predicate) {
        if (list.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        List<List<T>> lists = new ArrayList<>();
        boolean b = predicate.test(list.get(0));
        int len = list.size();
        int start = 0;
        for (int ii = 1; ii < len; ii++) {
            boolean t = predicate.test(list.get(ii));
            if (b != t) {
                lists.add(list.subList(start, ii));
                start = ii;
                b = t;
            }
        }
        lists.add(list.subList(start, len));
        return lists;
    }
}