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; 020 021import org.apache.reef.io.Tuple; 022import org.apache.reef.io.storage.util.TupleKeyComparator; 023 024import java.util.Comparator; 025import java.util.Iterator; 026import java.util.PriorityQueue; 027 028public class MergingIterator<T> implements Iterator<T> { 029 private final PriorityQueue<Tuple<T, Iterator<T>>> heap; 030 031 public MergingIterator(final Comparator<T> c, Iterator<T>[] its) { 032 this.heap = new PriorityQueue<Tuple<T, Iterator<T>>>(11, 033 new TupleKeyComparator<T, Iterator<T>>(c)); 034 035 for (Iterator<T> it : its) { 036 T b = it.hasNext() ? it.next() : null; 037 if (b != null) { 038 heap.add(new Tuple<>(b, it)); 039 } 040 } 041 } 042 043 @Override 044 public boolean hasNext() { 045 return heap.size() != 0; 046 } 047 048 @Override 049 public T next() { 050 Tuple<T, Iterator<T>> ret = heap.remove(); 051 if (ret.getValue().hasNext()) { 052 heap.add(new Tuple<>(ret.getValue().next(), ret.getValue())); 053 } 054 return ret.getKey(); 055 } 056 057 @Override 058 public void remove() { 059 throw new UnsupportedOperationException( 060 "Cannot remove entires from MergingIterator!"); 061 } 062}