001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.internal; 014 015import java.util.*; 016 017/** 018 * Implements a reversed iteration {@link Iterable} without altering the underlying list. 019 * 020 * @param <T> The entry type. 021 */ 022public class ReverseIterable<T> implements Iterable<T> { 023 private final List<T> list; 024 025 /** 026 * Constructor 027 * 028 * @param list The original list. 029 */ 030 public ReverseIterable(List<T> list) { 031 this.list = list; 032 } 033 034 /** 035 * Convenience method for constructing instances. 036 * 037 * @param list The original list. 038 * @return A new {@link ReverseIterable}. 039 */ 040 public static <T> ReverseIterable<T> of(List<T> list) { 041 return new ReverseIterable<>(list); 042 } 043 044 /** 045 * Convenience method for constructing instances. 046 * 047 * @param list The original list. 048 * @return A new {@link ReverseIterable}. 049 */ 050 public static <T> ReverseIterable<T> of(T[] list) { 051 return new ReverseIterable<>(Arrays.asList(list)); 052 } 053 054 @Override 055 public Iterator<T> iterator() { 056 final ListIterator<T> i = list.listIterator(list.size()); 057 058 return new Iterator<T>() { 059 @Override 060 public boolean hasNext() { return i.hasPrevious(); } 061 @Override 062 public T next() { return i.previous(); } 063 @Override 064 public void remove() { i.remove(); } 065 }; 066 } 067}