001/*
002 * Copyright (c) 2016-2017 Chris K Wensel <chris@wensel.net>. All Rights Reserved.
003 * Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
004 *
005 * Project and contact information: http://www.cascading.org/
006 *
007 * This file is part of the Cascading project.
008 *
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *     http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 */
021
022package cascading.util;
023
024import java.util.Iterator;
025
026/**
027 * Class SingleValueIterator is a convenience to creating an {@link Iterator} that returns one value for use
028 * with interfaces that only accept Iterator instances.
029 * <p>
030 * If given a {@code null} value, it will be assumed this Iterator instance has no value, and {@link #hasNext()}
031 * will return false.
032 */
033public class SingleValueIterator<Value> implements Iterator<Value>
034  {
035  public static final SingleValueIterator EMPTY = new SingleValueIterator();
036
037  private boolean hasValue = true;
038  protected Value value;
039
040  public SingleValueIterator()
041    {
042    this.hasValue = false;
043    }
044
045  public SingleValueIterator( Value value )
046    {
047    this.hasValue = value != null;
048    this.value = value;
049    }
050
051  @Override
052  public boolean hasNext()
053    {
054    return hasValue;
055    }
056
057  @Override
058  public Value next()
059    {
060    if( !hasValue )
061      throw new IllegalStateException( "no value available" );
062
063    try
064      {
065      return value;
066      }
067    finally
068      {
069      hasValue = false;
070      }
071    }
072
073  @Override
074  public void remove()
075    {
076    throw new UnsupportedOperationException( "unimplimented" );
077    }
078
079  public void reset( Value value )
080    {
081    this.hasValue = value != null;
082    this.value = value;
083    }
084  }