Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 530
alwayscurious Avatar asked Dec 23 '22 14:12

alwayscurious


2 Answers

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)));
like image 132
Eran Avatar answered Jan 16 '23 11:01

Eran


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.

like image 28
Naman Avatar answered Jan 16 '23 11:01

Naman