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.*; 016import java.util.function.*; 017 018/** 019 * Combines an {@link Iterable} with a {@link Function} so that you can map 020 * entries while iterating over them. 021 * 022 * @param <I> The unmapped type. 023 * @param <E> The mapped type. 024 */ 025public class MappedIterable<I,E> implements Iterable<E> { 026 027 final Iterator<I> i; 028 final Function<I,E> f; 029 030 /** 031 * Constructor. 032 * 033 * @param i The original iterable being wrapped. 034 * @param f The function to use to convert from unmapped to mapped types. 035 */ 036 protected MappedIterable(Iterable<I> i, Function<I,E> f) { 037 this.i = i.iterator(); 038 this.f = f; 039 } 040 041 /** 042 * Constructor. 043 * 044 * @param i The original iterable being wrapped. 045 * @param f The function to use to convert from unmapped to mapped types. 046 * @return A new iterable. 047 */ 048 public static <I,E> Iterable<E> of(Iterable<I> i, Function<I,E> f) { 049 return new MappedIterable<>(i, f); 050 } 051 052 @Override 053 public Iterator<E> iterator() { 054 return new Iterator<E>() { 055 @Override 056 public boolean hasNext() { 057 return i.hasNext(); 058 } 059 @Override 060 public E next() { 061 return f.apply(i.next()); 062 } 063 }; 064 } 065}