alwayscurious
alwayscurious

Reputation: 1165

Stream different data types

I'm getting my head around Streams API.

What is happening with the 2 in the first line? What data type is it treated as? Why doesn't this print true?

System.out.println(Stream.of("hi", "there",2).anyMatch(i->i=="2"));

The second part of this question is why doesn't the below code compile (2 is not in quotes)?

System.out.println(Stream.of("hi", "there",2).anyMatch(i->i==2));

Upvotes: 4

Views: 1133

Answers (2)

Naman
Naman

Reputation: 31868

You should instead make use of:

System.out.println(Stream.of("hi", "there",2).anyMatch(i->i.equals(2)));

The reason for that is the comparison within the anyMatch you're doing is for i which is an Object(from the stream) and is incompatible with an int.

Also, note that the first part compiles successfully since you are comparing an integer(object) with an object string "2" in there and hence returns false.

Upvotes: 3

Eran
Eran

Reputation: 393771

In the first snippet, you are creating a Stream of Objects. The 2 element is an Integer, so comparing it to the String "2" returns false.

In the second snippet, you can't compare an arbitrary Object to the int 2, since there is no conversion from Object to 2.

For the first snippet to return true, you have to change the last element of the Stream to a String (and also use equals instead of == in order not to rely on the String pool):

System.out.println(Stream.of("hi", "there", "2").anyMatch(i->i.equals("2")));

The second snippet can be fixed by using equals instead of ==, since equals exists for any Object:

System.out.println(Stream.of("hi", "there",2).anyMatch(i->i.equals(2)));

Upvotes: 7

Related Questions