假设我有一个对象列表,例如:-
[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/