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(Set<? extends CharSequence> keys, 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 CharSequence lastKey = null; 043 CharSequence curKey = findNextKey(); 044 045 private CharSequence findNextKey() { 046 while (k.hasNext()) { 047 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 final T v = map.get(key); 069 070 return new Map.Entry<CharSequence, T>() { 071 @Override 072 public CharSequence getKey() { 073 return key; 074 } 075 076 @Override 077 public T getValue() { 078 return v; 079 } 080 081 @Override 082 public T setValue(T v) { 083 throw new UnsupportedOperationException( 084 "No support for mutating values via iterator"); 085 } 086 }; 087 } 088 089 @Override 090 public void remove() { 091 map.remove(lastKey); 092 } 093 }; 094 } 095}