Reputation: 71
Say if I have, a list of objects like:-
[id = 1, age = 34, name = "abc"]
[id = 2, age = 34, name = "xyz"]
[id = 3, age = 34, name = "mno"]
then I need to convert them to :-
[1], [34], [abc],
[2], [34], [xyz],
[3], [34], [mno]
Upvotes: 2
Views: 4144
Reputation: 21
In this case you can use streams with map
and flatMap
methods:
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; }
}
Upvotes: 2
Reputation: 919
Say, you have class Person:
package stack.overflow.atest;
public class Person {
int id;
int age;
String name;
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}
As of Java 8 you can do something like this:
List<Object> result = Stream
.of(new Person(1, 23, "aaa"), new Person(2, 34, "bbb"))
.flatMap(p -> Stream.of(p.id, p.age, p.name))
.collect(Collectors.toList());
System.out.println("result: " + result);
this produces:
result: [1, 23, aaa, 2, 34, bbb]
Upvotes: 0
Reputation:
You can convert each Object to an array of its fields Object[]
as follows:
public static void main(String[] args) throws Exception {
List<Person> people = List.of(
new Person(1, 34, "abc"),
new Person(2, 34, "xyz"),
new Person(3, 34, "mno"));
Object[][] arr = people.stream()
.map(person -> new Object[]{
person.getId(), person.getAge(), person.getName()
}).toArray(Object[][]::new);
// output
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
//[1, 34, abc]
//[2, 34, xyz]
//[3, 34, mno]
}
static class Person {
int id;
int age;
String name;
public Person(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; }
}
Upvotes: 1