0

I have a little piece of code where i created my own java.util.stream realization.

I need to parametrize it using PECS rule. But either I didn't understand PECS rule well or my class designed bad - I don't know how to correctly implement it.

When I'm trying to implement it (? extends T) in filter() method realization, for example - I can't use foreach cycle.

Maybe you have some ideas? Thanks in advance.

public class Streams<T> {

private final List<T> list;
private List<T> resultList = new ArrayList<>();

private Streams(List<T> list) {
    this.list = list;
}

public static <E> Streams<E> of(List<E> list) {
    return new Streams<>(list);
}

public Streams<T> filter(Predicate<T> predicate) {
    for (T elem : list) {
        if (predicate.test(elem)) {
            resultList.add(elem);
        }
    }
    return this;
}

public Streams<T> transform(Function<? super T, ? extends T> function) {
    for (T elem : resultList) {
        resultList.set(resultList.indexOf(elem), function.apply(elem));
    }
    return this;
}

public <E, I> Map<E, I> toMap(Function<T, E> function1, Function<T, I> function2) {
    HashMap<E, I> map = new HashMap<>();
    for (T elem : resultList) {
        map.put(function1.apply(elem), function2.apply(elem));
    }
    return map;
  }
}
ruslangm
  • 674
  • 7
  • 19
  • The `Predicate` would need to be `Predicate super T>`: `predicate.test` *consumes* `elem`. – Andy Turner Aug 23 '16 at 15:14
  • Also: don't use `resultList.indexOf(elem)` to get the index: it will return the first index of a matching object. Use a `ListIterator`. Or, since you haven't prepopulated `resultList` before you call `transform`, just clear `resultList` and use `add`. – Andy Turner Aug 23 '16 at 15:16
  • thanks, I implemented it earlier but didn't know is it correct. thanks for the second answer too. – ruslangm Aug 23 '16 at 15:18

0 Answers0