7

In my application I want to convert an ArrayList of Integer objects into an ArrayList of Long objects. Is it possible?

Leigh
  • 28,765
  • 10
  • 55
  • 103
Shajeel Afzal
  • 5,913
  • 6
  • 43
  • 70
  • You can't do it directly. Maybe this post could help you: http://stackoverflow.com/questions/6690745/converting-integer-to-long – MikO Mar 18 '13 at 18:23
  • Ohhhh guyes. Why are you voting down this question? – Shajeel Afzal Mar 18 '13 at 18:25
  • It's not clear what you are exactly asking. You have to demonstrate it with some code. – Bhesh Gurung Mar 18 '13 at 18:26
  • The question is pretty clear, however it does not demonstrate any effort. With common questions such as this, you will typically get less down votes if you include *what* you have tried - and the results. – Leigh Mar 18 '13 at 18:27

3 Answers3

14

Not in a 1 liner.

List<Integer> ints = Arrays.asList(1,2,3,4,5,6,7,8,9);
int nInts = ints.size();
List<Long> longs = new ArrayList<Long>(nInts);
for (int i=0;i<nInts;++i) {
    longs.add(ints.get(i).longValue());
}

// Or you can use Lambda expression in Java 8

List<Integer> ints = Arrays.asList(1,2,3,4,5,6,7,8,9);
List<Long> longs = ints.stream()
        .mapToLong(Integer::longValue)
        .boxed().collect(Collectors.toList());
lagivan
  • 2,689
  • 22
  • 30
Tom
  • 43,583
  • 4
  • 41
  • 61
  • Brilliant!!! I was not able to convert it without your answer! Thank you very much! – Shajeel Afzal Mar 18 '13 at 18:37
  • Could anybody please give a hint, why is the boxed() method used in the second example? Since it's been worked here not with primitive 'int' values... – montie Aug 03 '23 at 19:41
6

No, you can't because, generics are not polymorphic.I.e., ArrayList<Integer> is not a subtype of ArrayList<Long>, thus the cast will fail. Thus, the only way is to Iterate over your List<Integer> and add it in List<Long>.

List<Long> longList = new ArrayList<Long>();
for(Integer i: intList){
longList.add(i.longValue());
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0
ArrayList<Long> longList = new ArrayList<Long>();

Iterator<Integer> it = intList.iterator();
while(it.hasNext())
{
    Integer obj = it.next();
    longList.add(obj); //will automatically convert Int to Long
}

Done....

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59
  • This doesn't even compile because these object types don't convert automatically. `longList.add((long)obj);` or any of the other solutions would work. – T Tse May 10 '23 at 20:13