IntStream rangeClosed unable to return value other than int

  • A+
Category:Languages

Why is this getting error? I thought map can return any value.

var s = IntStream.rangeClosed(1, 5).map(String::valueOf).collect(Collectors.toList()); 

| Error: | incompatible types: bad return type in method reference | java.lang.String cannot be converted to int | var s = IntStream.rangeClosed(1, 5).map(String::valueOf).collect(Collectors.toList()); |
^-------------^

 


Use mapToObj:

var s = IntStream.rangeClosed(1, 5).mapToObj(String::valueOf).collect(Collectors.toList()); 

map of IntStream can only map an int value to another int value.

mapToObj allows you to map an int value to a reference type, and thus transform the IntStream to a Stream<SomeReferenceType>.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: