简体   繁体   中英

What is the Best way to convert List<Byte> to List<Integer>

Which is the best method to convert Currently I am using something like below

List<Byte> bytes = new ArrayList<Byte>();
List<Object> integers = Arrays.asList(bytes.toArray());

Then each object inside integers needs to be typecast to Integer. Is there any other way in which I can achieve this?

With the standard JDK, here's how to do it

List<Byte> bytes = new ArrayList<Byte>();
// [...] Fill the bytes list somehow

List<Integer> integers = new ArrayList<Integer>();
for (Byte b : bytes) {
  integers.add(b == null ? null : b.intValue());
}

If you're sure, you don't have any null values in bytes :

for (byte b : bytes) {
  integers.add((int) b);
}

If Google's Guava available in your project:

// assume listofBytes is of type List<Byte>
List<Integer> listOfIntegers = Ints.asList(Ints.toArray(listOfBytes));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM