Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.*;

import java.util.function.Function;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> Iterable<T> concat(final Iterable<T>... collections) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    final Iterable<T>[] iterables = collections;
                    int iteratorIdx = 0;
                    Iterator<T> it = collections[0].iterator();

                    private synchronized void advanceCursor() {
                        while (!it.hasNext() && iteratorIdx < iterables.length) {
                            iteratorIdx += 1;
                            if (iteratorIdx == iterables.length) {
                                it = new Iterator<T>() {
                                    @Override
                                    public boolean hasNext() {
                                        return false;
                                    }

                                    @Override
                                    public T next() {
                                        throw new NoSuchElementException();
                                    }

                                    @Override
                                    public void remove() {
                                        throw new RuntimeException();
                                    }
                                };
                            } else {
                                it = iterables[iteratorIdx].iterator();
                            }
                        }
                    }

                    @Override
                    public synchronized boolean hasNext() {
                        advanceCursor();
                        return iteratorIdx != iterables.length && it.hasNext();
                    }

                    @Override
                    public synchronized T next() {
                        advanceCursor();
                        if (iteratorIdx == iterables.length)
                            throw new NoSuchElementException();
                        return it.next();
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

    public static <T1, T2> List<T2> concat(List<T1> lst, Function<T1, List<T2>> mapper) {
        List<T2> lst_ = new ArrayList<>(lst.size());
        for (T1 elem : lst)
            lst_.addAll(mapper.apply(elem));
        return lst_;
    }
}