-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?

Pimgd
  • 5,505
  • 1
  • 26
  • 44
Jude Niroshan
  • 3,973
  • 6
  • 36
  • 53
  • 1
    Maybe you should have a look at: http://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java – Flown Aug 13 '16 at 10:40
  • 2
    If you'd have read the accepted answer then you would get your answer. – Flown Aug 13 '16 at 10:46

1 Answers1

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

Community
  • 1
  • 1
Pimgd
  • 5,505
  • 1
  • 26
  • 44