
com.github.jeluard.guayaba.lang.Iterables2 Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of guayaba Show documentation
Show all versions of guayaba Show documentation
Simple extensions to Guava library with a Scala flavour
The newest version!
/**
* Copyright 2012 Julien Eluard
* This project includes software developed by Julien Eluard: https://github.com/jeluard/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jeluard.guayaba.lang;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Helper metchods for {@link Iterable}.
*/
public final class Iterables2 {
private Iterables2() {
}
/**
* Encapsulates a {@code value} from an {@link Iterable} with its associated {@code index}.
* @param
*/
public static final class Indexed {
public final int index;
public final T value;
public Indexed(final int index, final T value) {
this.index = index;
this.value = Preconditions.checkNotNull(value, "null value");
}
}
/**
* Augment iterated value with an `index` corresponding to its position in the {@link Iterable}.
*
* @param
* @param iterable
* @return
*/
public static Iterable> withIndex(final Iterable iterable) {
Preconditions.checkNotNull(iterable, "null iterable");
return new Iterable>() {
@Override
public Iterator> iterator() {
return new AbstractIterator>() {
private final Iterator iterator = iterable.iterator();
private int index = 0;
@Override
protected Indexed computeNext() {
try {
return new Indexed(this.index++, this.iterator.next());
} catch (NoSuchElementException e) {
//Don't rely on hasNext/next as this would complexify concurrent access support.
return endOfData();
}
}
};
}
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy