Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Copyright 2014 Google Inc. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;

import java.util.List;
import java.util.ListIterator;

public class Main {
    /**
     * Introduces overlap into a series of lists. 
     * @param before # of elements from the end of the previous list to prepend
     * @param after # of elements from the beginning of the next list to append
     */
    public static <T> List<List<T>> overlap(List<List<T>> lists, int before, int after) {

        if (before < 0) {
            throw new IllegalArgumentException("Value of before cannot be negative");
        }
        if (after < 0) {
            throw new IllegalArgumentException("Value of after cannot be negative");
        }

        ListIterator<List<T>> iter = lists.listIterator();

        List<List<T>> result = new ArrayList<List<T>>();
        for (; iter.hasNext();) {
            List<T> current = new ArrayList<T>(iter.next());
            List<T> prev = before > 0 ? findPrevious(iter) : null;
            List<T> next = after > 0 ? findNext(iter) : null;
            if (prev != null) {
                List<T> overlap = prev.subList(prev.size() - before, prev.size());
                current.addAll(0, overlap);
            }
            if (next != null) {
                List<T> overlap = next.subList(0, after);
                current.addAll(overlap);
            }
            result.add(current);
        }

        return result;
    }

    private static <T> T findPrevious(ListIterator<T> iter) {
        T prev = null;
        iter.previous(); // rewind
        if (iter.hasPrevious()) {
            prev = iter.previous();
            iter.next(); // come back
        }
        iter.next(); // come back
        return prev;
    }

    private static <T> T findNext(ListIterator<T> iter) {
        T next = null;
        if (iter.hasNext()) {
            next = iter.next();
            iter.previous(); // come back
        }
        return next;
    }
}