I have an InfiniteListImpl class which implements the interface InfiniteList, and I am having difficulty creating the filter method. Here is what I have for my InfiniteListImpl class so far:
import java.util.function.Supplier; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.BiFunction; import java.util.Optional; public class InfiniteListImpl<T> implements InfiniteList<T>{ Supplier<Optional<T>> head; Supplier<InfiniteListImpl<T>> tail; public InfiniteListImpl(Supplier<Optional<T>> head, Supplier<InfiniteListImpl<T>> tail){ this.head = head; this.tail = tail; } public static <T> InfiniteListImpl<T> generate(Supplier<? extends T> generator){ return new InfiniteListImpl<T>( () -> Optional.ofNullable(generator.get()), () -> InfiniteListImpl.generate(generator)); } public static <T> InfiniteListImpl<T> iterate(T seed, Function<? super T, ? extends T> func){ return new InfiniteListImpl<T>( () -> Optional.ofNullable(seed), () -> InfiniteListImpl.iterate(func.apply(seed), func)); } public InfiniteListImpl<T> get(){ Optional<T> headElement = this.head.get(); if (headElement.isPresent()){ System.out.println(headElement.get()); } return tail.get(); } public <R> InfiniteListImpl<R> map(Function<? super T, ? extends R> mapper){ return new InfiniteListImpl<R>( () -> head.get().map(mapper), () -> tail.get().map(mapper)); } public InfiniteListImpl<T> filter(Predicate<? super T> pred){ }
The filter method is supposed to fulfill these following test cases:
jshell> InfiniteList<Integer> ifl = InfiniteList.generate(() -> 1).map(x -> x * 2) jshell> ifl instanceof InfiniteListImpl $.. ==> true jshell> ifl = InfiniteList.iterate(1, x -> x + 1).filter(x -> x % 2 == 0) jshell> ifl instanceof InfiniteListImpl $.. ==> true jshell> InfiniteListImpl<Integer> ifl1 = InfiniteListImpl.iterate(1, x -> x + 1).map(x -> x * 2) jshell> InfiniteListImpl<Integer> ifl2 = ifl1.get().get() 2 4 jshell> ifl2 = ifl1.get().get() 2 4 jshell> ifl1 = InfiniteListImpl.iterate(1, x -> x + 1).filter(x -> x % 2 == 0).get().get() 2 jshell> ifl2 = ifl1.get().get().get() 4 jshell> ifl1 = InfiniteListImpl.iterate(1, x -> x + 1).map(x -> x * 2).map(x -> x - 1).get().get() 1 3 jshell> ifl1 = InfiniteListImpl.iterate(1, x -> x + 1).filter(x -> x % 2 == 0).filter(x -> x < 4).get().get().get().get() 2
Any advice on how I should go about creating my filter method?