refactor: rename fluent interface module

This commit is contained in:
Ilkka Seppälä
2024-05-26 08:55:06 +03:00
parent 506d64cf40
commit bd5ff136c2
15 changed files with 2 additions and 2 deletions
@@ -0,0 +1,131 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.fluentinterface.app;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable;
import java.util.List;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.function.Predicate;
import lombok.extern.slf4j.Slf4j;
/**
* The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API.
* Those interfaces tend to mimic domain specific languages, so they can nearly be read as human
* languages.
*
* <p>In this example two implementations of a {@link FluentIterable} interface are given. The
* {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world
* applications. The {@link LazyFluentIterable} is evaluated on termination. Their usage is
* demonstrated with a simple number list that is filtered, transformed and collected. The result is
* printed afterward.
*/
@Slf4j
public class App {
/**
* Program entry point.
*/
public static void main(String[] args) {
var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68);
prettyPrint("The initial list contains: ", integerList);
var firstFiveNegatives = SimpleFluentIterable
.fromCopyOf(integerList)
.filter(negatives())
.first(3)
.asList();
prettyPrint("The first three negative values are: ", firstFiveNegatives);
var lastTwoPositives = SimpleFluentIterable
.fromCopyOf(integerList)
.filter(positives())
.last(2)
.asList();
prettyPrint("The last two positive values are: ", lastTwoPositives);
SimpleFluentIterable
.fromCopyOf(integerList)
.filter(number -> number % 2 == 0)
.first()
.ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber));
var transformedList = SimpleFluentIterable
.fromCopyOf(integerList)
.filter(negatives())
.map(transformToString())
.asList();
prettyPrint("A string-mapped list of negative numbers contains: ", transformedList);
var lastTwoOfFirstFourStringMapped = LazyFluentIterable
.from(integerList)
.filter(positives())
.first(4)
.last(2)
.map(number -> "String[" + 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(number -> LOGGER.info("Last amongst first two negatives: {}", number));
}
private static Function<Integer, String> transformToString() {
return integer -> "String[" + integer + "]";
}
private static Predicate<? super Integer> negatives() {
return integer -> integer < 0;
}
private static Predicate<? super Integer> positives() {
return integer -> integer > 0;
}
private static <E> void prettyPrint(String prefix, Iterable<E> iterable) {
prettyPrint(", ", prefix, iterable);
}
private static <E> void prettyPrint(
String delimiter, String prefix,
Iterable<E> iterable
) {
var joiner = new StringJoiner(delimiter, prefix, ".");
iterable.forEach(e -> joiner.add(e.toString()));
LOGGER.info(joiner.toString());
}
}
@@ -0,0 +1,109 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.fluentinterface.fluentiterable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
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 interface defines common operations, but doesn't aim to
* be complete. It was inspired by Guava's com.google.common.collect.FluentIterable.
*
* @param <E> is the class of objects the iterable contains
*/
public interface FluentIterable<E> extends Iterable<E> {
/**
* Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy
* the 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 a filtered FluentIterable
*/
FluentIterable<E> filter(Predicate<? super E> predicate);
/**
* Returns an Optional containing the first element of this iterable if present, else returns
* Optional.empty().
*
* @return the first element after the iteration is evaluated
*/
Optional<E> first();
/**
* Evaluates the iteration and leaves only the count first elements.
*
* @return the first count elements as an Iterable
*/
FluentIterable<E> first(int count);
/**
* Evaluates the iteration and returns the last element. This is a terminating operation.
*
* @return the last element after the iteration is evaluated
*/
Optional<E> last();
/**
* Evaluates the iteration and leaves only the count last elements.
*
* @return the last counts elements as an Iterable
*/
FluentIterable<E> last(int count);
/**
* Transforms this FluentIterable into a new one containing objects of the type T.
*
* @param function a function that transforms an instance of E into an instance of T
* @param <T> the target type of the transformation
* @return a new FluentIterable of the new type
*/
<T> FluentIterable<T> map(Function<? super E, T> function);
/**
* Returns the contents of this Iterable as a List.
*
* @return a List representation of this Iterable
*/
List<E> asList();
/**
* Utility method that iterates over iterable and adds the contents to a list.
*
* @param iterable the iterable to collect
* @param <E> the type of the objects to iterate
* @return a list with all objects of the given iterator
*/
static <E> List<E> copyToList(Iterable<E> iterable) {
var copy = new ArrayList<E>();
iterable.forEach(copy::add);
return copy;
}
}
@@ -0,0 +1,82 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.fluentinterface.fluentiterable.lazy;
import java.util.Iterator;
/**
* This class is used to realize LazyFluentIterables. It decorates a given iterator. Does not
* support consecutive hasNext() calls.
*
* @param <E> Iterable Collection of Elements of Type E
*/
public abstract class DecoratingIterator<E> implements Iterator<E> {
protected final Iterator<E> fromIterator;
private E next;
/**
* Creates an iterator that decorates the given iterator.
*/
public DecoratingIterator(Iterator<E> fromIterator) {
this.fromIterator = fromIterator;
}
/**
* Precomputes and saves the next element of the Iterable. null is considered as end of data.
*
* @return true if a next element is available
*/
@Override
public final boolean hasNext() {
next = computeNext();
return next != null;
}
/**
* Returns the next element of the Iterable.
*
* @return the next element of the Iterable, or null if not present.
*/
@Override
public final E next() {
if (next == null) {
return fromIterator.next();
} else {
final var result = next;
next = null;
return result;
}
}
/**
* Computes the next object of the Iterable. Can be implemented to realize custom behaviour for an
* iteration process. null is considered as end of data.
*
* @return the next element of the Iterable.
*/
public abstract E computeNext();
}
@@ -0,0 +1,240 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
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.Function;
import java.util.function.Predicate;
import lombok.RequiredArgsConstructor;
/**
* This is a lazy implementation of the FluentIterable interface. It evaluates all chained
* operations when a terminating operation is applied.
*
* @param <E> the type of the objects the iteration is about
*/
@RequiredArgsConstructor
public class LazyFluentIterable<E> implements FluentIterable<E> {
private final Iterable<E> iterable;
/**
* This constructor can be used to implement anonymous subclasses of the LazyFluentIterable.
*/
protected LazyFluentIterable() {
iterable = this;
}
/**
* Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy
* the 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 a new FluentIterable object that decorates the source iterable
*/
@Override
public FluentIterable<E> filter(Predicate<? super E> predicate) {
return new LazyFluentIterable<>() {
@Override
public Iterator<E> iterator() {
return new DecoratingIterator<>(iterable.iterator()) {
@Override
public E computeNext() {
while (fromIterator.hasNext()) {
var candidate = fromIterator.next();
if (predicate.test(candidate)) {
return candidate;
}
}
return null;
}
};
}
};
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
*
* @return an Optional containing the first object of this Iterable
*/
@Override
public Optional<E> first() {
var resultIterator = first(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
}
/**
* 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.
*/
@Override
public FluentIterable<E> first(int count) {
return new LazyFluentIterable<>() {
@Override
public Iterator<E> iterator() {
return new DecoratingIterator<>(iterable.iterator()) {
int currentIndex;
@Override
public E computeNext() {
if (currentIndex < count && fromIterator.hasNext()) {
var candidate = fromIterator.next();
currentIndex++;
return candidate;
}
return null;
}
};
}
};
}
/**
* Can be used to collect objects from the iteration. Is a terminating operation.
*
* @return an Optional containing the last object of this Iterable
*/
@Override
public Optional<E> last() {
var resultIterator = last(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
}
/**
* Can be used to collect objects from the Iterable. Is a terminating operation. This operation is
* memory intensive, because the contents of this Iterable are collected into a List, when the
* next object is requested.
*
* @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<E> last(int count) {
return new LazyFluentIterable<>() {
@Override
public Iterator<E> iterator() {
return new DecoratingIterator<>(iterable.iterator()) {
private int stopIndex;
private int totalElementsCount;
private List<E> list;
private int currentIndex;
@Override
public E computeNext() {
initialize();
while (currentIndex < stopIndex && fromIterator.hasNext()) {
currentIndex++;
fromIterator.next();
}
if (currentIndex >= stopIndex && fromIterator.hasNext()) {
return fromIterator.next();
}
return null;
}
private void initialize() {
if (list == null) {
list = new ArrayList<>();
iterable.forEach(list::add);
totalElementsCount = list.size();
stopIndex = totalElementsCount - count;
}
}
};
}
};
}
/**
* Transforms this FluentIterable into a new one containing objects of the type T.
*
* @param function a function that transforms an instance of E into an instance of T
* @param <T> the target type of the transformation
* @return a new FluentIterable of the new type
*/
@Override
public <T> FluentIterable<T> map(Function<? super E, T> function) {
return new LazyFluentIterable<>() {
@Override
public Iterator<T> iterator() {
return new DecoratingIterator<>(null) {
final Iterator<E> oldTypeIterator = iterable.iterator();
@Override
public T computeNext() {
if (oldTypeIterator.hasNext()) {
E candidate = oldTypeIterator.next();
return function.apply(candidate);
} else {
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<E> asList() {
return FluentIterable.copyToList(iterable);
}
@Override
public Iterator<E> iterator() {
return new DecoratingIterator<>(iterable.iterator()) {
@Override
public E computeNext() {
return fromIterator.hasNext() ? fromIterator.next() : null;
}
};
}
/**
* Constructors FluentIterable from given iterable.
*
* @return a FluentIterable from a given iterable. Calls the LazyFluentIterable constructor.
*/
public static <E> FluentIterable<E> from(Iterable<E> iterable) {
return new LazyFluentIterable<>(iterable);
}
}
@@ -0,0 +1,215 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.fluentinterface.fluentiterable.simple;
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.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import lombok.RequiredArgsConstructor;
/**
* This is a simple implementation of the FluentIterable interface. It evaluates all chained
* operations eagerly. This implementation would be costly to be utilized in real applications.
*
* @param <E> the type of the objects the iteration is about
*/
@RequiredArgsConstructor
public class SimpleFluentIterable<E> implements FluentIterable<E> {
private final Iterable<E> iterable;
/**
* Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy
* the 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
*/
@Override
public final FluentIterable<E> filter(Predicate<? super E> predicate) {
var iterator = iterator();
while (iterator.hasNext()) {
var nextElement = iterator.next();
if (!predicate.test(nextElement)) {
iterator.remove();
}
}
return this;
}
/**
* Can be used to collect objects from the Iterable. Is a terminating operation.
*
* @return an option of the first object of the Iterable
*/
@Override
public final Optional<E> first() {
var resultIterator = first(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
}
/**
* Can be used to collect objects from the Iterable. 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<E> first(int count) {
var iterator = iterator();
var currentCount = 0;
while (iterator.hasNext()) {
iterator.next();
if (currentCount >= count) {
iterator.remove();
}
currentCount++;
}
return this;
}
/**
* Can be used to collect objects from the Iterable. Is a terminating operation.
*
* @return an option of the last object of the Iterable
*/
@Override
public final Optional<E> last() {
var list = last(1).asList();
if (list.isEmpty()) {
return Optional.empty();
}
return Optional.of(list.get(0));
}
/**
* Can be used to collect objects from the Iterable. 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<E> last(int count) {
var remainingElementsCount = getRemainingElementsCount();
var iterator = iterator();
var 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 T.
*
* @param function a function that transforms an instance of E into an instance of T
* @param <T> the target type of the transformation
* @return a new FluentIterable of the new type
*/
@Override
public final <T> FluentIterable<T> map(Function<? super E, T> function) {
var temporaryList = new ArrayList<T>();
this.forEach(e -> temporaryList.add(function.apply(e)));
return from(temporaryList);
}
/**
* Collects all remaining objects of this Iterable into a list.
*
* @return a list with all remaining objects of this Iterable
*/
@Override
public List<E> asList() {
return toList(iterable.iterator());
}
/**
* Constructs FluentIterable from iterable.
*
* @return a FluentIterable from a given iterable. Calls the SimpleFluentIterable constructor.
*/
public static <E> FluentIterable<E> from(Iterable<E> iterable) {
return new SimpleFluentIterable<>(iterable);
}
public static <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) {
var copy = FluentIterable.copyToList(iterable);
return new SimpleFluentIterable<>(copy);
}
@Override
public Iterator<E> iterator() {
return iterable.iterator();
}
@Override
public void forEach(Consumer<? super E> action) {
iterable.forEach(action);
}
@Override
public Spliterator<E> spliterator() {
return iterable.spliterator();
}
/**
* Find the count of remaining objects of current iterable.
*
* @return the count of remaining objects of the current Iterable
*/
public final int getRemainingElementsCount() {
var counter = 0;
for (var ignored : this) {
counter++;
}
return counter;
}
/**
* Collects the remaining objects of the given iterator into a List.
*
* @return a new List with the remaining objects.
*/
public static <E> List<E> toList(Iterator<E> iterator) {
var copy = new ArrayList<E>();
iterator.forEachRemaining(copy::add);
return copy;
}
}