My question is: Given a list of persons, return all students.
Here are my classes:
Person class
public class Person {
}
Student class
public class Student extends Person {
}
Method
public static List<Student> findStudents(List<Person> list) {
return list.stream()
.filter(person -> person instanceof Student)
.collect(Collectors.toList());
}
I'm getting a compile error: incompatible types: inference variable T has incompatible bounds
How do I return all the students from the list using stream without getting this error.
Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b). Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4].
Stream class has toArray() method to convert Stream to Array, but there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion methods between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.
That means list. stream(). filter(i -> i >= 3); does not change original list. All stream operations are non-interfering (none of them modify the data source), as long as the parameters that you give to them are non-interfering too.
A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are various methods to convert List to Stream in Java:
To convert an infinite stream into list, we must limit the stream to a finite number of elements. Given example will work in case of stream of primitives. Program output. 5. Conclusion Clearly, We can use Collectors.toList () function is variety of ways to collect stream elements into an list in all usescases.
Sometimes, the incompatible types error can occur due to basic negligence, where the only mistake is an accidental mis-declaration of a variable’s type (Fig. 3 (a)). In these instances, the issue is quite obvious and simply correcting the type declaration solves the problem (Fig. 3 (b)).
Incompatible, in this context, means that the source type is both different from and unconvertible (by means of automatic type casting) to the declared type. This might seem like a syntax error, but it is a logical error discovered in the semantic phase of compilation.
return list.stream()
.filter(Student.class::isInstance)
.map(Student.class::cast)
.collect(Collectors.toList());
It should be a cast there, otherwise, it's still a Stream<Person>
. The instanceof
check doesn't perform any cast.
Student.class::isInstance
and Student.class::cast
is just a preference of mine, you could go with p -> p instanceof Student
and p -> (Student)p
respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With