public class Lists {
private Lists() { } // can't be instantiated
public static List<T> join(List<T>... lists) {List<T> result = new ArrayList<T>();for(List<T> list : lists) {result.addAll(list);}return results;}
}
然后你可以做这样的事情
import static Lists.join;List<T> result = join(list1, list2, list3, list4);
/*** @param smallLists* @return one big list containing all elements of the small ones, in the same order.*/public static <E> List<E> concatenate (final List<E> ... smallLists){final ArrayList<E> bigList = new ArrayList<E>();for (final List<E> list: smallLists){bigList.addAll(list);}return bigList;}
public static <T> List<T> merge(List<T>... args) {final List<T> result = new ArrayList<>();
for (List<T> list : args) {result.addAll(list);}
return result;}
public static final EnumSet<MyType> CATEGORY_A = EnumSet.of(A_1, A_2);public static final EnumSet<MyType> CATEGORY_B = EnumSet.of(B_1, B_2, B_3);
public static final List<MyType> ALL =Collections.unmodifiableList(new ArrayList<MyType>(CATEGORY_A.size() + CATEGORY_B.size())\{\{addAll(CATEGORY_A);addAll(CATEGORY_B);}});
import java.util.AbstractList;import java.util.List;
/*** The {@code ConcatList} is a lightweight view of two {@code List}s.* <p>* This implementation is <em>not</em> thread-safe even though the underlying lists can be.** @param <E>* the type of elements in this list*/public class ConcatList<E> extends AbstractList<E> {
/** The first underlying list. */private final List<E> list1;/** The second underlying list. */private final List<E> list2;
/*** Constructs a new {@code ConcatList} from the given two lists.** @param list1* the first list* @param list2* the second list*/public ConcatList(final List<E> list1, final List<E> list2) {this.list1 = list1;this.list2 = list2;}
@Overridepublic E get(final int index) {return getList(index).get(getListIndex(index));}
@Overridepublic E set(final int index, final E element) {return getList(index).set(getListIndex(index), element);}
@Overridepublic void add(final int index, final E element) {getList(index).add(getListIndex(index), element);}
@Overridepublic E remove(final int index) {return getList(index).remove(getListIndex(index));}
@Overridepublic int size() {return list1.size() + list2.size();}
@Overridepublic boolean contains(final Object o) {return list1.contains(o) || list2.contains(o);}
@Overridepublic void clear() {list1.clear();list2.clear();}
/*** Returns the index within the corresponding list related to the given index.** @param index* the index in this list** @return the index of the underlying list*/private int getListIndex(final int index) {final int size1 = list1.size();return index >= size1 ? index - size1 : index;}
/*** Returns the list that corresponds to the given index.** @param index* the index in this list** @return the underlying list that corresponds to that index*/private List<E> getList(final int index) {return index >= list1.size() ? list2 : list1;}
}