13

I have a method which takes a list of integer as parameter. I currently have a list of long and want to convert it to a list of integer so I wrote :

  List<Integer> student =
  studentLong.stream()
  .map(Integer::valueOf)
  .collect(Collectors.toList());

But I received an error:

method "valueOf" can not be resolved. 

Is it actually possible to convert a list of long to a list of integer?

shmosel
  • 49,289
  • 6
  • 73
  • 138
user3369592
  • 1,367
  • 5
  • 21
  • 43

1 Answers1

20

You should use a mapToInt with Long::intValue in order to extract the int value:

List<Integer> student = studentLong.stream()
           .mapToInt(Long::intValue)
           .boxed()
           .collec‌t(Collectors.toList(‌​))

The reason you're getting method "valueOf" can not be resolved. is because there is no signature of Integer::valueOf which accepts Long as an argument.

EDIT
Per Holger's comment below, we can also do:

List<Integer> student = studentLong.stream()
           .map(Long::intValue)
           .collec‌t(Collectors.toList(‌​))
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • 5
    Instead of `.mapToInt(Long::intValue) .boxed()` you can simply use `.map(Long::intValue)`. – Holger Nov 29 '17 at 11:14
  • Thanks @Holger I'll add it to the answer! – Nir Alfasi Feb 15 '18 at 16:34
  • 1
    I'm trying to do it the other way around, Integer to Long. Without boxed() it doesn't compile. `.stream().mapToLong(Integer::longValue).boxed().collect(Collectors.toList())` – juanmf Apr 05 '18 at 03:18
  • @Holger : .map doesnt convert to primitive int? – javaAndBeyond Sep 24 '20 at 17:59
  • 1
    @user2296988 `map` on a `Stream<…>` always returns a `Stream<…>`, never an `IntStream`. When you use `map(Long::intValue)` on a `Stream`, it will invoke `intValue` on the `Long` objects, followed by an implicit boxing conversion to `Integer`. When you want an `IntStream`, you need `mapToInt`, but in this specific case, an `IntStream` is not intended. – Holger Sep 25 '20 at 06:27