001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.io.storage.util; 020 021import org.apache.reef.io.ExternalMap; 022 023import java.util.Iterator; 024import java.util.Map; 025import java.util.NoSuchElementException; 026import java.util.Set; 027 028public class GetAllIterable<T> implements 029 Iterable<Map.Entry<CharSequence, T>> { 030 private final Set<? extends CharSequence> keys; 031 private final ExternalMap<T> map; 032 033 public GetAllIterable(final Set<? extends CharSequence> keys, final ExternalMap<T> map) { 034 this.keys = keys; 035 this.map = map; 036 } 037 038 @Override 039 public Iterator<Map.Entry<CharSequence, T>> iterator() { 040 final Iterator<? extends CharSequence> k = keys.iterator(); 041 return new Iterator<Map.Entry<CharSequence, T>>() { 042 private CharSequence lastKey = null; 043 private CharSequence curKey = findNextKey(); 044 045 private CharSequence findNextKey() { 046 while (k.hasNext()) { 047 final CharSequence next = k.next(); 048 if (map.containsKey(next)) { 049 return next; 050 } 051 } 052 return null; 053 } 054 055 @Override 056 public boolean hasNext() { 057 return curKey != null; 058 } 059 060 @Override 061 public Map.Entry<CharSequence, T> next() { 062 final CharSequence key = curKey; 063 curKey = findNextKey(); 064 lastKey = key; 065 if (key == null) { 066 throw new NoSuchElementException(); 067 } 068 069 final T v = map.get(key); 070 071 return new Map.Entry<CharSequence, T>() { 072 @Override 073 public CharSequence getKey() { 074 return key; 075 } 076 077 @Override 078 public T getValue() { 079 return v; 080 } 081 082 @Override 083 public T setValue(final T v) { 084 throw new UnsupportedOperationException( 085 "No support for mutating values via iterator"); 086 } 087 }; 088 } 089 090 @Override 091 public void remove() { 092 map.remove(lastKey); 093 } 094 }; 095 } 096}