001/* Copyright (C) 2013 TU Dortmund 002 * This file is part of AutomataLib, http://www.automatalib.net/. 003 * 004 * AutomataLib is free software; you can redistribute it and/or 005 * modify it under the terms of the GNU Lesser General Public 006 * License version 3.0 as published by the Free Software Foundation. 007 * 008 * AutomataLib is distributed in the hope that it will be useful, 009 * but WITHOUT ANY WARRANTY; without even the implied warranty of 010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 011 * Lesser General Public License for more details. 012 * 013 * You should have received a copy of the GNU Lesser General Public 014 * License along with AutomataLib; if not, see 015 * http://www.gnu.de/documents/lgpl.en.html. 016 */ 017package net.automatalib.commons.util.collections; 018 019import java.util.Iterator; 020import java.util.NoSuchElementException; 021 022public abstract class IterableUtil { 023 024 private static final Iterator<?> EMPTY_ITERATOR = new Iterator<Object>() { 025 /* 026 * (non-Javadoc) 027 * @see java.util.Iterator#hasNext() 028 */ 029 @Override 030 public boolean hasNext() { 031 return false; 032 } 033 034 /* 035 * (non-Javadoc) 036 * @see java.util.Iterator#next() 037 */ 038 @Override 039 public Object next() { 040 throw new NoSuchElementException(); 041 } 042 043 /* 044 * (non-Javadoc) 045 * @see java.util.Iterator#remove() 046 */ 047 @Override 048 public void remove() { 049 throw new UnsupportedOperationException(); 050 } 051 052 }; 053 054 @SafeVarargs 055 public static <T> Iterator<T> concat(Iterator<? extends T> ...iterators) { 056 return new ConcatIterator<>(iterators); 057 } 058 059 @SafeVarargs 060 public static <T> Iterable<T> concat(final Iterable<? extends T> ...iterables) { 061 return new Iterable<T>() { 062 @Override 063 public Iterator<T> iterator() { 064 @SuppressWarnings("unchecked") 065 Iterator<? extends T>[] iterators = new Iterator[iterables.length]; 066 for(int i = 0; i < iterables.length; i++) 067 iterators[i] = iterables[i].iterator(); 068 return concat(iterators); 069 } 070 }; 071 } 072 073 @SuppressWarnings("unchecked") 074 public static <T> Iterator<T> emptyIterator() { 075 return (Iterator<T>)EMPTY_ITERATOR; 076 } 077 078 public static <T> Iterator<T> unmodifiableIterator(Iterator<T> iterator) { 079 return new UnmodifiableIterator<>(iterator); 080 } 081 082 083 public static <T> Iterable<T> unmodifiableIterable(final Iterable<T> iterable) { 084 return new Iterable<T>() { 085 @Override 086 public Iterator<T> iterator() { 087 return unmodifiableIterator(iterable.iterator()); 088 } 089 }; 090 } 091 092 // Prevent inheritance 093 private IterableUtil() {} 094 095}