问题
I have a LinkedList < Integer > with big size (3912984 or more) and I wanna copy these elements in a byte array. The integers are 0 or 1, so I don't need any change of size for array, I want just to copy elements one by one, exactly how they are. Of course, I know the simplest way is :
for(int i = 0; i < list.size(); i++)
array[i] = (byte)(int) list.get(i);
But this method is too slow and my program doesn't end before hours ! Can you know another way (faster, something like Buffer.BlockCopy() of .NET) or I have to change data structures?
回答1:
There is byteValue() method available in Number class. Number is extended by Integer, Double, Float etc.
List<Integer> list = getNumbers();
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext())
{
Integer i = iterator.next()
byteArray[index] = i.byteValue();
}
You can also use java.nio.MappedByteBuffer
class for block copy. see http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html.
MappedByteBuffer is equivalent to Buffer.BlockCopy() in .NET
回答2:
Another way to do it with Java 8:
List<Integer> enteros = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toList());
Byte[] bytes = enteros.stream().map(entero -> entero.byteValue()).toArray(Byte[]::new);
Here another complex example to test the conversion time:
List<Integer> enteros = new LinkedList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println("Init list: " + LocalTime.now().format(formatter));
// Fill array with 0 and 1
for(int i = 0; i < 9999999; i++) enteros.add(ThreadLocalRandom.current().nextInt(0, 2));
System.out.println("List complete: " + LocalTime.now().format(formatter));
System.out.println("Init list convert: " + LocalTime.now().format(formatter));
Byte[] bytes = enteros.stream().map(entero -> entero.byteValue()).toArray(Byte[]::new);
System.out.println("End convert! " + LocalTime.now().format(formatter));
回答3:
// example input list
List<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(0);
list.add(1);
list.add(0);
list.add(1);
list.add(1);
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (int element : list) {
out.writeUTF(Integer.toString(element));
}
byte[] bytes = baos.toByteArray();
// read from byte array
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
String element = in.readUTF();
System.out.println(element);
}
来源:https://stackoverflow.com/questions/25460810/list-of-integers-into-byte-array