Sankalp
Sankalp

Reputation: 1288

Incomparable types capture and int in Java streams allMatch()

I have a X509 certificate. I'm trying to extract all the SANs from it. After that, I want to make sure that SAN is of type dNSName - that is the first entry in the list should be an integer with value 2. Ref- https://docs.oracle.com/javase/7/docs/api/java/security/cert/X509Certificate.html#getSubjectAlternativeNames()

The expression below fails to compile saying "Incomparable types capture and int"

certificate.getSubjectAlternativeNames().stream().allMatch(x -> x.get(0) == 2)

However, the following expression returns True.

certificate.getSubjectAlternativeNames().stream().allMatch(x -> x.get(0).toString().equals("2"))

I don't want to convert it to String and then match it to a string. I simply want an Integer comparison here. How can I do it?

Upvotes: 1

Views: 101

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

I simply want an Integer comparison here.

You should be able to simply call Object#equals on the first element of the List:

certificate.getSubjectAlternativeNames()
           .stream()
           .allMatch(x -> x.get(0).equals(2))

Because the generic type of the List is a capture type ?, the compiler won't be able to infer what type of Object is in it, and won't allow you to compare it to a primitive (directly).

List<List<?>> list = List.of(List.of(1, 2, 3));

System.out.println(list.stream().allMatch(x -> x.get(0).equals(1)));

Output:

true

Upvotes: 3

Related Questions