杰瑞科技汇

Java List如何转byte数组?

Of course! Converting a Java List to a byte array is a common task, but the approach depends entirely on what the List contains.

Java List如何转byte数组?-图1
(图片来源网络,侵删)

There are two primary scenarios:

  1. The List contains Byte objects. This is the most direct conversion.
  2. The List contains other data types (like String, Integer, custom objects). This requires serialization.

Let's break down both scenarios with clear examples.


Scenario 1: The List contains Byte objects

This is the simplest case. You need to iterate through the List and unbox each Byte object into a primitive byte to store in your byte[] array.

Method A: The Classic Loop (Easy to Understand)

This method is straightforward and easy for beginners to read and understand.

Java List如何转byte数组?-图2
(图片来源网络,侵删)
import java.util.Arrays;
import java.util.List;
public class ListOfBytesToByteArray {
    public static void main(String[] args) {
        // 1. Create a List of Byte objects
        List<Byte> byteList = Arrays.asList((byte) 10, (byte) 20, (byte) 30, (byte) 40);
        // 2. Create a byte array with the same size as the list
        byte[] byteArray = new byte[byteList.size()];
        // 3. Iterate and copy each byte from the list to the array
        for (int i = 0; i < byteList.size(); i++) {
            // The .get(i) returns a Byte object, which is automatically "unboxed" to a primitive byte
            byteArray[i] = byteList.get(i);
        }
        // 4. Print the result
        System.out.println("Original List: " + byteList);
        System.out.println("Converted byte[]: " + Arrays.toString(byteArray));
        System.out.println("Hex representation: " + bytesToHex(byteArray));
    }
    // Helper method to print byte array in a readable hex format
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString();
    }
}

Output:

Original List: [10, 20, 30, 40]
Converted byte[]: [10, 20, 30, 40]
Hex representation: 0A 14 1E 28 

Method B: Using Java 8 Streams (Modern & Concise)

This is a more modern, functional approach using Java Streams. It's more compact and often preferred in modern codebases.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ListOfBytesStream {
    public static void main(String[] args) {
        List<Byte> byteList = Arrays.asList((byte) 10, (byte) 20, (byte) 30, (byte) 40);
        // Convert List<Byte> to byte[] using a stream
        byte[] byteArray = byteList.stream()
                                  .mapToByte(Byte::byteValue) // Convert Byte to primitive byte
                                  .toArray();                   // Collect into an array
        System.out.println("Original List: " + byteList);
        System.out.println("Converted byte[] (Stream): " + Arrays.toString(byteArray));
    }
}

Output:

Original List: [10, 20, 30, 40]
Converted byte[] (Stream): [10, 20, 30, 40]

Scenario 2: The List contains complex data (Strings, Objects, etc.)

If your List contains anything other than Byte objects (e.g., List<String>, List<MyCustomObject>), you cannot directly convert it to a byte[]. You must first serialize the data into a byte stream.

Java List如何转byte数组?-图3
(图片来源网络,侵删)

Serialization is the process of converting an object into a byte stream so that it can be saved to a file, sent over a network, or stored in memory. The most common way to do this in Java is with ObjectOutputStream.

Example: Serializing a List<String>

Let's convert a List<String> into a byte[].

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.List;
public class ListToByteArraySerialization {
    public static void main(String[] args) {
        // 1. Create a List of Strings
        List<String> stringList = Arrays.asList("Hello", "World", "from", "Java");
        try {
            // 2. Create a ByteArrayOutputStream to hold the byte stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 3. Create an ObjectOutputStream that writes to the ByteArrayOutputStream
            try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
                // 4. Write the entire List to the stream
                // This is the key step: the List is serialized.
                oos.writeObject(stringList);
                // 5. Get the byte array from the ByteArrayOutputStream
                byte[] byteArray = bos.toByteArray();
                System.out.println("Original List: " + stringList);
                System.out.println("Serialized byte[] length: " + byteArray.length);
                System.out.println("Hex representation: " + bytesToHex(byteArray));
                // --- To prove it works, let's deserialize it back ---
                java.io.ByteArrayInputStream bis = new java.io.ByteArrayInputStream(byteArray);
                try (java.io.ObjectInputStream ois = new java.io.ObjectInputStream(bis)) {
                    @SuppressWarnings("unchecked")
                    List<String> deserializedList = (List<String>) ois.readObject();
                    System.out.println("Deserialized List: " + deserializedList);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    // Helper method to print byte array in a readable hex format
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString();
    }
}

Output:

Original List: [Hello, World, from, Java]
Serialized byte[] length: 119
Hex representation: AC ED 00 05 74 00 09 48 65 6C 6C 6F 00 05 57 6F 72 6C 64 00 04 66 72 6F 6D 00 04 4A 61 76 61 75 72 00 05 73 69 7A 65 70 78 00 00 00 02 77 78 00 00 00 01 74 
Deserialized List: [Hello, World, from, Java]

⚠️ Important Considerations for Serialization

  1. The List and its elements must be Serializable. If you try to serialize an object that doesn't implement the java.io.Serializable interface, you'll get a NotSerializableException.
  2. The format is not human-readable. The output is a binary format, not text.
  3. The format is JVM-dependent. A byte array serialized on one JVM (e.g., OpenJDK 17) might not be deserializable on a different JVM (e.g., an older version or a different vendor). This makes it unsuitable for long-term data storage or interchange between different systems unless you control both ends.
  4. Performance: Serialization can be slower than direct conversion and produces larger byte arrays.

Summary: Which Method to Use?

Your Goal What's in your List? Recommended Method
Get a simple array of primitive bytes Byte objects Scenario 1: Use a for-loop or a Java 8 Stream.
Send data over a network or save to a file String, Integer, etc. Scenario 2: Use ObjectOutputStream for serialization.
Convert a List of Strings to bytes String objects Don't serialize the whole list. Use String.getBytes(StandardCharsets.UTF_8) on each element and then combine. This is more efficient and standard.
分享:
扫描分享到社交APP
上一篇
下一篇