#184 Fluent interface pattern, lazy fluentiterable added

This commit is contained in:
Hannes Pernpeintner
2015-08-22 20:22:00 +02:00
parent 02162994a3
commit ded21b70ac
5 changed files with 539 additions and 153 deletions

View File

@ -1,14 +1,14 @@
package com.iluwatar.fluentinterface;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import static java.lang.String.valueOf;
public class App {
public static void main(String[] args) {
@ -34,35 +34,49 @@ public class App {
}};
prettyPrint("The initial list contains: ", integerList);
List<Integer> firstFiveNegatives = FluentIterable.from(integerList)
List<Integer> firstFiveNegatives = SimpleFluentIterable.from(integerList)
.filter(negatives())
.first(3)
.asList();
prettyPrint("The first three negative values are: ", firstFiveNegatives);
List<Integer> lastTwoPositives = FluentIterable.from(integerList)
List<Integer> lastTwoPositives = SimpleFluentIterable.from(integerList)
.filter(positives())
.last(2)
.asList();
prettyPrint("The last two positive values are: ", lastTwoPositives);
FluentIterable.from(integerList)
SimpleFluentIterable.from(integerList)
.filter(number -> number%2 == 0)
.first()
.ifPresent(evenNumber -> System.out.println(String.format("The first even number is: %d", evenNumber)));
List<String> transformedList = FluentIterable.from(integerList)
List<String> transformedList = SimpleFluentIterable.from(integerList)
.filter(negatives())
.map(transformToString())
.asList();
prettyPrint("A string-mapped list of negative numbers contains: ", transformedList);
List<String> lastTwoOfFirstFourStringMapped = LazyFluentIterable.from(integerList)
.filter(positives())
.first(4)
.last(2)
.map(number -> "String[" + String.valueOf(number) + "]")
.asList();
prettyPrint("The lazy list contains the last two of the first four positive numbers mapped to Strings: ", lastTwoOfFirstFourStringMapped);
LazyFluentIterable.from(integerList)
.filter(negatives())
.first(2)
.last()
.ifPresent(lastOfFirstTwo -> System.out.println(String.format("The last of the first two negatives is: %d", lastOfFirstTwo)));
}
private static Function<Integer, String> transformToString() {
return integer -> "String[" + String.valueOf(integer) + "]";
return integer -> "String[" + valueOf(integer) + "]";
}
private static Predicate<? super Integer> negatives() {
return integer -> (integer < 0);

View File

@ -1,6 +1,9 @@
package com.iluwatar.fluentinterface.fluentiterable;
import java.util.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
@ -8,116 +11,49 @@ import java.util.function.Predicate;
/**
* The FluentIterable is a more convenient implementation of the common iterable interface based
* on the fluent interface design pattern.
* This implementation demonstrates a possible way to implement this functionality, but
* This interface defines common operations, but
* doesn't aim to be complete. It was inspired by Guava's com.google.common.collect.FluentIterable.
* @param <TYPE> is the class of objects the iterable contains
*/
public class FluentIterable<TYPE> implements Iterable<TYPE> {
private final Iterable<TYPE> iterable;
public interface FluentIterable<TYPE> extends Iterable<TYPE> {
/**
* This constructor creates a copy of a given iterable's contents.
* @param iterable the iterable this interface copies to work on.
*/
protected FluentIterable(Iterable<TYPE> iterable) {
ArrayList<TYPE> copy = new ArrayList<>();
Iterator<TYPE> iterator = iterable.iterator();
while (iterator.hasNext()) {
copy.add(iterator.next());
}
this.iterable = copy;
}
/**
* Iterates over all elements of this iterator and filters them.
* Filters the iteration with the given predicate.
* @param predicate the condition to test with for the filtering. If the test
* is negative, the tested object is removed by the iterator.
* @return the same FluentIterable with a filtered collection
* @return a filtered FluentIterable
*/
public final FluentIterable<TYPE> filter(Predicate<? super TYPE> predicate) {
Iterator<TYPE> iterator = iterator();
while (iterator.hasNext()) {
TYPE nextElement = iterator.next();
if(!predicate.test(nextElement)) {
iterator.remove();
}
}
return this;
}
FluentIterable<TYPE> filter(Predicate<? super TYPE> predicate);
/**
* Uses the Iterable interface's forEach method to apply a given function
* for each object of the iterator.
* @param action the action for each object
* @return the same FluentIterable with an untouched collection
* for each object of the iterator. This is a terminating operation.
*/
public final FluentIterable<TYPE> forEachDo(Consumer<? super TYPE> action) {
iterable.forEach(action);
return this;
}
void forEachDo(Consumer<? super TYPE> action);
/**
* Can be used to collect objects from the iteration.
* @return an option of the first object of the iteration
* Evaluates the iteration and returns the first element. This is a terminating operation.
* @return the first element after the iteration is evaluated
*/
public final Optional<TYPE> first() {
List<TYPE> list = first(1).asList();
if(list.isEmpty()) {
return Optional.empty();
}
return Optional.of(list.get(0));
}
Optional<TYPE> first();
/**
* Can be used to collect objects from the iteration.
* @param count defines the number of objects to return
* @return the same FluentIterable with a collection decimated to a maximum of 'count' first objects.
* Evaluates the iteration and leaves only the count first elements.
* @return the first count elements as an Iterable
*/
public final FluentIterable<TYPE> first(int count) {
Iterator<TYPE> iterator = iterator();
int currentCount = 0;
while (iterator.hasNext()) {
iterator.next();
if(currentCount >= count) {
iterator.remove();
}
currentCount++;
}
return this;
}
FluentIterable<TYPE> first(int count);
/**
* Can be used to collect objects from the iteration.
* @return an option of the last object of the iteration
* Evaluates the iteration and returns the last element. This is a terminating operation.
* @return the last element after the iteration is evaluated
*/
public final Optional<TYPE> last() {
List<TYPE> list = last(1).asList();
if(list.isEmpty()) {
return Optional.empty();
}
return Optional.of(list.get(0));
}
Optional<TYPE> last();
/**
* Can be used to collect objects from the iteration.
* @param count defines the number of objects to return
* @return the same FluentIterable with a collection decimated to a maximum of 'count' last objects
* Evaluates the iteration and leaves only the count last elements.
* @return the last counts elements as an Iterable
*/
public final FluentIterable<TYPE> last(int count) {
int remainingElementsCount = getRemainingElementsCount();
Iterator<TYPE> iterator = iterator();
int currentIndex = 0;
while (iterator.hasNext()) {
iterator.next();
if(currentIndex < remainingElementsCount - count) {
iterator.remove();
}
currentIndex++;
}
return this;
}
FluentIterable<TYPE> last(int count);
/**
* Transforms this FluentIterable into a new one containing objects of the type NEW_TYPE.
@ -125,65 +61,18 @@ public class FluentIterable<TYPE> implements Iterable<TYPE> {
* @param <NEW_TYPE> the target type of the transformation
* @return a new FluentIterable of the new type
*/
public final <NEW_TYPE> FluentIterable<NEW_TYPE> map(Function<? super TYPE, NEW_TYPE> function) {
List<NEW_TYPE> temporaryList = new ArrayList();
Iterator<TYPE> iterator = iterator();
while (iterator.hasNext()) {
temporaryList.add(function.apply(iterator.next()));
}
return from(temporaryList);
}
<NEW_TYPE> FluentIterable<NEW_TYPE> map(Function<? super TYPE, NEW_TYPE> function);
List<TYPE> asList();
/**
* Collects all remaining objects of this iteration into a list.
* @return a list with all remaining objects of this iteration
* Utility method that iterates over iterable and adds the contents to a list.
* @param iterable the iterable to collect
* @param <TYPE> the type of the objects to iterate
* @return a list with all objects of the given iterator
*/
public List<TYPE> asList() {
return toList(iterable.iterator());
}
/**
* @return a FluentIterable from a given iterable. Calls the FluentIterable constructor.
*/
public static final <TYPE> FluentIterable<TYPE> from(Iterable<TYPE> iterable) {
return new FluentIterable<>(iterable);
}
@Override
public Iterator<TYPE> iterator() {
return iterable.iterator();
}
@Override
public void forEach(Consumer<? super TYPE> action) {
iterable.forEach(action);
}
@Override
public Spliterator<TYPE> spliterator() {
return iterable.spliterator();
}
/**
* @return the count of remaining objects in the current iteration
*/
public final int getRemainingElementsCount() {
int counter = 0;
Iterator<TYPE> iterator = iterator();
while(iterator.hasNext()) {
iterator.next();
counter++;
}
return counter;
}
/**
* Collects the remaining objects of the given iterators iteration into an List.
* @return a new List with the remaining objects.
*/
public static <TYPE> List<TYPE> toList(Iterator<TYPE> iterator) {
List<TYPE> copy = new ArrayList<>();
static <TYPE> List<TYPE> copyToList(Iterable<TYPE> iterable) {
ArrayList<TYPE> copy = new ArrayList<>();
Iterator<TYPE> iterator = iterable.iterator();
while (iterator.hasNext()) {
copy.add(iterator.next());
}

View File

@ -0,0 +1,53 @@
package com.iluwatar.fluentinterface.fluentiterable.lazy;
import java.util.Iterator;
/**
* This class is used to realize LazyFluentIterables. It decorates
* a given iterator.
* @param <TYPE>
*/
public abstract class DecoratingIterator<TYPE> implements Iterator<TYPE> {
protected final Iterator<TYPE> fromIterator;
private TYPE next = null;
/**
* Creates an iterator that decorates the given iterator.
* @param fromIterator
*/
public DecoratingIterator(Iterator<TYPE> fromIterator) {
this.fromIterator = fromIterator;
}
/**
* Precomputes and caches the next element of the iteration.
* @return true if a next element is available
*/
@Override
public final boolean hasNext() {
next = computeNext();
return next != null;
}
/**
* Returns the next element of the iteration. This implementation caches it.
* If no next element is cached, it is computed.
* @return the next element obf the iteration
*/
@Override
public final TYPE next() {
TYPE result = next;
next = null;
result = (result == null ? fromIterator.next() : result);
return result;
}
/**
* Computes the next object of the iteration. Can be implemented to
* realize custom behaviour for an iteration process.
* @return
*/
public abstract TYPE computeNext();
}

View File

@ -0,0 +1,236 @@
package com.iluwatar.fluentinterface.fluentiterable.lazy;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* This is a lazy implementation of the FluentIterable interface. It evaluates
* all chained operations when a terminating operation is applied.
* @param <TYPE> the type of the objects the iteration is about
*/
public class LazyFluentIterable<TYPE> implements FluentIterable<TYPE> {
private final Iterable<TYPE> iterable;
/**
* This constructor creates a new LazyFluentIterable. It wraps the
* given iterable.
* @param iterable the iterable this FluentIterable works on.
*/
protected LazyFluentIterable(Iterable<TYPE> iterable) {
this.iterable = iterable;
}
/**
* This constructor can be used to implement anonymous subclasses
* of the LazyFluentIterable.
*/
protected LazyFluentIterable() {
iterable = this;
}
/**
* Adds a filter operation to the operation chain and returns a new iterable.
* @param predicate the condition to test with for the filtering. If the test
* is negative, the tested object is removed by the iterator.
* @return a new FluentIterable object that decorates the source iterable
*/
@Override
public FluentIterable<TYPE> filter(Predicate<? super TYPE> predicate) {
return new LazyFluentIterable<TYPE>() {
@Override
public Iterator<TYPE> iterator() {
return new DecoratingIterator<TYPE>(iterable.iterator()) {
@Override
public TYPE computeNext() {
while(true) {
if(fromIterator.hasNext()) {
TYPE candidate = fromIterator.next();
if(!predicate.test(candidate)) {
continue;
}
return candidate;
}
return null;
}
}
};
}
};
}
/**
* Uses the Iterable interface's forEach method to apply a given function
* for each object of the iterator. Is a terminating operation.
* @param action the action for each object
*/
@Override
public void forEachDo(Consumer<? super TYPE> action) {
Iterator<TYPE> newIterator = iterable.iterator();
while(newIterator.hasNext()) {
action.accept(newIterator.next());
}
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @return an option of the first object of the iteration
*/
@Override
public Optional<TYPE> first() {
Optional result = Optional.empty();
List<TYPE> list = first(1).asList();
if(!list.isEmpty()) {
result = Optional.of(list.get(0));
}
return result;
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @param count defines the number of objects to return
* @return the same FluentIterable with a collection decimated to a maximum of 'count' first objects.
*/
@Override
public FluentIterable<TYPE> first(int count) {
return new LazyFluentIterable<TYPE>() {
@Override
public Iterator<TYPE> iterator() {
return new DecoratingIterator<TYPE>(iterable.iterator()) {
int currentIndex = 0;
@Override
public TYPE computeNext() {
if(currentIndex < count) {
if(fromIterator.hasNext()) {
TYPE candidate = fromIterator.next();
currentIndex++;
return candidate;
}
}
return null;
}
};
}
};
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @return an option of the last object of the iteration
*/
@Override
public Optional<TYPE> last() {
Optional result = Optional.empty();
List<TYPE> list = last(1).asList();
if(!list.isEmpty()) {
result = Optional.of(list.get(0));
}
return result;
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @param count defines the number of objects to return
* @return the same FluentIterable with a collection decimated to a maximum of 'count' last objects
*/
@Override
public FluentIterable<TYPE> last(int count) {return new LazyFluentIterable<TYPE>() {
@Override
public Iterator<TYPE> iterator() {
return new DecoratingIterator<TYPE>(iterable.iterator()) {
int currentIndex = 0;
@Override
public TYPE computeNext() {
List<TYPE> list = new ArrayList<>();
Iterator<TYPE> newIterator = iterable.iterator();
while(newIterator.hasNext()) {
list.add(newIterator.next());
}
int totalElementsCount = list.size();
int stopIndex = totalElementsCount - count;
TYPE candidate = null;
while(currentIndex < stopIndex && fromIterator.hasNext()) {
currentIndex++;
fromIterator.next();
}
if(currentIndex >= stopIndex && fromIterator.hasNext()) {
candidate = fromIterator.next();
}
return candidate;
}
};
}
};
}
/**
* Transforms this FluentIterable into a new one containing objects of the type NEW_TYPE.
* @param function a function that transforms an instance of TYPE into an instance of NEW_TYPE
* @param <NEW_TYPE> the target type of the transformation
* @return a new FluentIterable of the new type
*/
@Override
public <NEW_TYPE> FluentIterable<NEW_TYPE> map(Function<? super TYPE, NEW_TYPE> function) {
return new LazyFluentIterable<NEW_TYPE>() {
@Override
public Iterator<NEW_TYPE> iterator() {
return new DecoratingIterator<NEW_TYPE>(null) {
Iterator<TYPE> oldTypeIterator = iterable.iterator();
@Override
public NEW_TYPE computeNext() {
while(true) {
if(oldTypeIterator.hasNext()) {
TYPE candidate = oldTypeIterator.next();
return function.apply(candidate);
}
return null;
}
}
};
}
};
}
/**
* Collects all remaining objects of this iteration into a list.
* @return a list with all remaining objects of this iteration
*/
@Override
public List<TYPE> asList() {
List<TYPE> copy = FluentIterable.copyToList(iterable);
return copy;
}
@Override
public Iterator<TYPE> iterator() {
return new DecoratingIterator<TYPE>(iterable.iterator()) {
@Override
public TYPE computeNext() {
return fromIterator.next();
}
};
}
/**
* @return a FluentIterable from a given iterable. Calls the LazyFluentIterable constructor.
*/
public static final <TYPE> FluentIterable<TYPE> from(Iterable<TYPE> iterable) {
return new LazyFluentIterable<>(iterable);
}
}

View File

@ -0,0 +1,194 @@
package com.iluwatar.fluentinterface.fluentiterable.simple;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterable;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* This is a simple implementation of the FluentIterable interface. It evaluates
* all chained operations eagerly.
* @param <TYPE> the type of the objects the iteration is about
*/
public class SimpleFluentIterable<TYPE> implements FluentIterable<TYPE> {
private final Iterable<TYPE> iterable;
/**
* This constructor creates a copy of a given iterable's contents.
* @param iterable the iterable this interface copies to work on.
*/
protected SimpleFluentIterable(Iterable<TYPE> iterable) {
List<TYPE> copy = FluentIterable.copyToList(iterable);
this.iterable = copy;
}
/**
* Iterates over all elements of this iterator and filters them.
* @param predicate the condition to test with for the filtering. If the test
* is negative, the tested object is removed by the iterator.
* @return the same FluentIterable with a filtered collection
*/
@Override
public final FluentIterable<TYPE> filter(Predicate<? super TYPE> predicate) {
Iterator<TYPE> iterator = iterator();
while (iterator.hasNext()) {
TYPE nextElement = iterator.next();
if(!predicate.test(nextElement)) {
iterator.remove();
}
}
return this;
}
/**
* Uses the Iterable interface's forEach method to apply a given function
* for each object of the iterator. Is a terminating operation.
* @param action the action for each object
*/
@Override
public void forEachDo(Consumer<? super TYPE> action) {
iterable.forEach(action);
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @return an option of the first object of the iteration
*/
@Override
public final Optional<TYPE> first() {
List<TYPE> list = first(1).asList();
if(list.isEmpty()) {
return Optional.empty();
}
return Optional.of(list.get(0));
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @param count defines the number of objects to return
* @return the same FluentIterable with a collection decimated to a maximum of 'count' first objects.
*/
@Override
public final FluentIterable<TYPE> first(int count) {
Iterator<TYPE> iterator = iterator();
int currentCount = 0;
while (iterator.hasNext()) {
iterator.next();
if(currentCount >= count) {
iterator.remove();
}
currentCount++;
}
return this;
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @return an option of the last object of the iteration
*/
@Override
public final Optional<TYPE> last() {
List<TYPE> list = last(1).asList();
if(list.isEmpty()) {
return Optional.empty();
}
return Optional.of(list.get(0));
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
* @param count defines the number of objects to return
* @return the same FluentIterable with a collection decimated to a maximum of 'count' last objects
*/
@Override
public final FluentIterable<TYPE> last(int count) {
int remainingElementsCount = getRemainingElementsCount();
Iterator<TYPE> iterator = iterator();
int currentIndex = 0;
while (iterator.hasNext()) {
iterator.next();
if(currentIndex < remainingElementsCount - count) {
iterator.remove();
}
currentIndex++;
}
return this;
}
/**
* Transforms this FluentIterable into a new one containing objects of the type NEW_TYPE.
* @param function a function that transforms an instance of TYPE into an instance of NEW_TYPE
* @param <NEW_TYPE> the target type of the transformation
* @return a new FluentIterable of the new type
*/
@Override
public final <NEW_TYPE> FluentIterable<NEW_TYPE> map(Function<? super TYPE, NEW_TYPE> function) {
List<NEW_TYPE> temporaryList = new ArrayList();
Iterator<TYPE> iterator = iterator();
while (iterator.hasNext()) {
temporaryList.add(function.apply(iterator.next()));
}
return from(temporaryList);
}
/**
* Collects all remaining objects of this iteration into a list.
* @return a list with all remaining objects of this iteration
*/
@Override
public List<TYPE> asList() {
return toList(iterable.iterator());
}
/**
* @return a FluentIterable from a given iterable. Calls the SimpleFluentIterable constructor.
*/
public static final <TYPE> FluentIterable<TYPE> from(Iterable<TYPE> iterable) {
return new SimpleFluentIterable<>(iterable);
}
@Override
public Iterator<TYPE> iterator() {
return iterable.iterator();
}
@Override
public void forEach(Consumer<? super TYPE> action) {
iterable.forEach(action);
}
@Override
public Spliterator<TYPE> spliterator() {
return iterable.spliterator();
}
/**
* @return the count of remaining objects in the current iteration
*/
public final int getRemainingElementsCount() {
int counter = 0;
Iterator<TYPE> iterator = iterator();
while(iterator.hasNext()) {
iterator.next();
counter++;
}
return counter;
}
/**
* Collects the remaining objects of the given iterators iteration into an List.
* @return a new List with the remaining objects.
*/
public static <TYPE> List<TYPE> toList(Iterator<TYPE> iterator) {
List<TYPE> copy = new ArrayList<>();
while (iterator.hasNext()) {
copy.add(iterator.next());
}
return copy;
}
}