杰瑞科技汇

Java List如何高效转byte数组?

  1. List<String> 转换为 byte[]:最常见的情况,通常需要指定字符集(如 UTF-8)。
  2. List<Integer>List<Byte> 转换为 byte[]:处理数字列表。
  3. List<Object>(自定义对象列表)转换为 byte[]:需要将对象序列化。
  4. List<byte[]>(字节数组列表)转换为 byte[]:合并多个字节数组。

List<String> 转换为 byte[]

这是最典型的情况,你需要将列表中的所有字符串连接成一个大的字符串,然后将其转换为字节数组。关键在于必须指定字符集(Charset),否则在不同系统上可能会产生不同的结果。

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

方法:使用 String.join()String.getBytes()

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
public class ListOfStringToBytes {
    public static void main(String[] args) {
        // 1. 准备一个 String 类型的 List
        List<String> stringList = Arrays.asList("Hello", " ", "World", "!", "你好");
        // 2. 定义一个分隔符(可选,也可以用空字符串 "" 连接)
        String delimiter = ""; // 直接连接,不加任何东西
        // String delimiter = ","; // 用逗号连接,会变成 "Hello, ,World,!,你好"
        // 3. 使用 String.join() 将 List 合并为一个 String
        //    注意:这里传入的是 List 的元素类型,而不是 List 本身
        String combinedString = String.join(delimiter, stringList);
        System.out.println("合并后的字符串: " + combinedString); // 输出: Hello World!你好
        // 4. 使用指定的字符集将 String 转换为 byte[]
        //    强烈推荐使用 StandardCharsets.UTF_8,避免平台默认编码带来的问题
        byte[] byteArray = combinedString.getBytes(StandardCharsets.UTF_8);
        // 5. 打印结果
        System.out.println("转换后的 byte[] 长度: " + byteArray.length);
        System.out.println("byte[] 内容: " + Arrays.toString(byteArray));
    }
}

输出示例:

合并后的字符串: Hello World!你好
转换后的 byte[] 长度: 14
byte[] 内容: [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, -28, -67, -96]

注意:中文字符 "你" 和 "好" 在 UTF-8 编码下占用多个字节,byteArray 的长度不是 12。


List<Integer>List<Byte> 转换为 byte[]

当列表中存储的是数字时,转换逻辑是直接将每个数字转换为一个字节。

方法:使用 Java 8 的 Stream

这种方法简洁且高效。

Java List如何高效转byte数组?-图2
(图片来源网络,侵删)
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ListOfIntegerToBytes {
    public static void main(String[] args) {
        // 1. 准备一个 Integer 类型的 List
        List<Integer> integerList = Arrays.asList(72, 101, 108, 108, 111); // 对应 "Hello"
        // 2. 使用 Stream 进行转换
        //    mapToInt(Integer::byteValue) 将每个 Integer 转换为 byte (primitive type)
        //    toArray() 将流收集为一个 byte[]
        byte[] byteArray = integerList.stream()
                                      .mapToInt(Integer::byteValue)
                                      .toArray();
        // 3. 打印结果
        System.out.println("转换后的 byte[]: " + Arrays.toString(byteArray));
        // List 本身就是 List<Byte>
        List<Byte> byteList = Arrays.asList((byte) 72, (byte) 101, (byte) 108, (byte) 108, (byte) 111);
        byte[] byteArrayFromByteList = byteList.stream()
                                                .mapToByte(Byte::byteValue)
                                                .toArray();
        System.out.println("从 List<Byte> 转换的 byte[]: " + Arrays.toString(byteArrayFromByteList));
    }
}

输出示例:

转换后的 byte[]: [72, 101, 108, 108, 111]
从 List<Byte> 转换的 byte[]: [72, 101, 108, 108, 111]

List<Object>(自定义对象列表)转换为 byte[]

如果你想将一个包含自定义 Java 对象的列表转换为 byte[],你需要将这些对象序列化(Serialize),序列化是将对象状态转换为字节流的过程,以便可以存储在文件或内存中,或通过网络传输。

方法:使用对象序列化

  1. 自定义对象必须实现 java.io.Serializable 接口,这是一个标记接口,不需要实现任何方法。
  2. 使用 ObjectOutputStream 将对象写入一个 ByteArrayOutputStream
import java.io.*;
import java.util.ArrayList;
import java.util.List;
// 1. 自定义对象,必须实现 Serializable 接口
class User implements Serializable {
    private static final long serialVersionUID = 1L; // 推荐添加,用于版本控制
    private String name;
    private int age;
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + "}";
    }
}
public class ListOfObjectToBytes {
    public static void main(String[] args) {
        // 2. 创建一个自定义对象列表
        List<User> userList = new ArrayList<>();
        userList.add(new User("Alice", 30));
        userList.add(new User("Bob", 25));
        try {
            // 3. 创建一个 ByteArrayOutputStream 作为目标
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 4. 创建一个 ObjectOutputStream,并将其连接到 baos
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            // 5. 将整个 List 写入输出流
            //    ObjectOutputStream 会自动处理列表的序列化
            oos.writeObject(userList);
            // 6. 从 baos 获取字节数组
            byte[] byteArray = baos.toByteArray();
            // 7. 关闭流
            oos.close();
            baos.close();
            System.out.println("对象列表已成功序列化为 byte[]");
            System.out.println("byte[] 长度: " + byteArray.length);
            System.out.println("byte[] 内容: " + Arrays.toString(byteArray));
            // --- 反序列化示例(验证) ---
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            ObjectInputStream ois = new ObjectInputStream(bais);
            @SuppressWarnings("unchecked")
            List<User> deserializedList = (List<User>) ois.readObject();
            System.out.println("\n反序列化后的列表:");
            deserializedList.forEach(System.out::println);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

输出示例:


对象列表已成功序列化为 byte[]
byte[] 长度: 161
byte[] 内容: [123, 114, 0, 20, 115, 101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111, 110, 85, 73, 68, 120, 114, 0, 23, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 65, 114, 114, 97, 121, 76, 105, 115, 116, 120, 80, 0, 1, 76, 0, 4, 115, 105, 122, 101, 114, 116, 120, 70, 0, 4, 101, 108, 101, 109, 101, 110, 116, 116, 0, 5, 101, 108, 109, 101, 110, 116, 73, 120, 114, 0, 11, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 65, 114, 114, 97, 121, 76, 105, 115, 116, 36, 69, 108, 101, 109, 101, 110, 116, 101, 100, 83, 101, 114, 105, 97, 108, 105, 122, 97, 98, 108, 101, 120, 70, 0, 4, 100, 97, 116, 97, 91, 120, 112, 0, 0, 0, 2, 120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