java - Java中如何将Object的属性值转换为数组?

标签 java arrays object java-8

假设我有一个对象列表,例如:-

[id = 1, age = 34, name = "abc"]
[id = 2, age = 34, name = "xyz"]
[id = 3, age = 34, name = "mno"]

然后我需要将它们转换为:-

[1], [34], [abc],
[2], [34], [xyz],
[3], [34], [mno]

最佳答案

在这种情况下,您可以使用 map 的流和 flatMap方法:

public static void main(String[] args) {
    MyClass obj = new MyClass(1, 50, "John");
    MyClass obj2 = new MyClass(2, 30, "Michał");
    List<MyClass> list = Arrays.asList(obj, obj2);
    List<Object> all = list.stream()
            .map(o -> Arrays.asList(o.getId(), o.getAge(), o.getName()))
            .flatMap(Collection::stream)
            .collect(Collectors.toList());

    all.forEach(element -> System.out.println(element));
}
public static class MyClass {
    private final int id;
    private final int age;
    private final String name;

    public MyClass(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() { return id; }
    public int getAge() { return age; }
    public String getName() { return name; }
}

关于java - Java中如何将Object的属性值转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66476747/

相关文章:

java - android应用未执行

python - 如何根据特定行中的值对 numpy 数组进行排序?

arrays - 为什么在数组扩展中使用 Stride 非法创建临时数组

javascript - JQuery - 将twodim 数组传递给$.post 失败

c# - 仅反序列化根/特定 json 对象 C#

没有 Graphics2D 的 Java 图形 : Constructing FontMetrics from Font,

java - Junit 5 无法解析方法的参数

javascript - 在 javascript 对象中使用 html 对象作为属性 "name"有什么危险吗?

java - 无法使用 Eclipse 内存分析器打开 HPROF 文件

Javascript:消失的对象属性