-2

I wonder why this code even compiles. Because here what we have is a Predicate which its type could be String or any of its super type. Obviously, length() is not available in Object class which is suitable for this predicate.

Predicate<? super String> predicate = s -> s.length() > 3;
Stream.of("cat", "bat", "rat", "doggy").filter(predicate).forEach(System.out::println);

Can anyone describe a situation where we must need these type of a bounded type predicate?

2

1 Answer 1

4

Because Stream.of(T t...) returns a Stream<T> and you are putting in 4 Strings, the output of Stream.of("cat", "bat", "rat", "doggy") will be a Stream<String>.

After that, it's only logical that a Predicate<? super String> can be used to filter a Stream<String>. Were you to create a list that contains strings and numbers, but is typed to be List<String> (for instance, through this bit of code...)

    List<String> list = new ArrayList<>();
    list.add("cat");
    list.add("bat");
    list.add("rat");
    list.add("doggy");

    List list2 = list;
    list2.add(1);

Then

list.stream().filter(predicate).forEach(System.out::println);

Will throw a ClassCastException at runtime when it hits the Integer.


As for a situation where you'd want to use ? super Something, you can read the answer to the question @Flown linked earlier: Difference between <? super T> and <? extends T> in Java

Not the answer you're looking for? Browse other questions tagged or ask your own question.