-2
我有一個類,說所有人的字符串屬性。我有一個ArrayList < Person>。我想將此ArrayList < Person>轉換爲列表< String []>。我如何使用java轉換它?如何將對象列表轉換爲java中的字符串數組列表?
我有一個類,說所有人的字符串屬性。我有一個ArrayList < Person>。我想將此ArrayList < Person>轉換爲列表< String []>。我如何使用java轉換它?如何將對象列表轉換爲java中的字符串數組列表?
假設人類的每個屬性是字符串數組中的一個項目,下面將做的工作:
Person類:
public class Person {
private String title;
private String firstName;
private String lastName;
public Person(String title, String firstName, String lastName) {
super();
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
PersonConverter類別:
import java.util.ArrayList;
import java.util.List;
public class PersonConverter {
public List<String[]> convertPersonList(List<Person> list) {
List<String[]> result = new ArrayList<>();
for (Person p : list) {
result.add(convertPerson(p));
}
return result;
}
private String[] convertPerson(Person p) {
String[] persontAttributes = new String[3];
persontAttributes[0] = p.getTitle();
persontAttributes[1] = p.getFirstName();
persontAttributes[2] = p.getLastName();
return persontAttributes;
}
}
測試:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
//create a person list
List<Person> personList = new ArrayList<>();
Person john = new Person("Mr.", "John", "Lenonn");
Person paul = new Person("Sir", "Paul", "McCartney");
personList.add(john);
personList.add(paul);
//create an instance of the person converter
PersonConverter pc = new PersonConverter();
//perform the conversion
List<String[]> convertedList = pc.convertPersonList(personList);
//print the result to the console
for (String[] stringArray : convertedList) {
for (String s : stringArray) {
System.out.println(s);
}
System.out.println();
}
}
}
此打印出:
Mr.
John
Lenonn
Sir
Paul
McCartney
我不確定我是否清楚您要求的內容,但您始終可以對您的人員進行簡單循環。
ArrayList<Person> people = new ArrayList<Person>();
List<String[]> everyonesAtt = new ArrayList<String[]>();
for (Person person : people) {
everyonesAtt.add(person.getAttributes());
}
和Person類的例子:
public class Person {
private String name;
private String surname;
public String[] getAttributes(){
String[] atts = {name, surname};
return atts;
}
}
你的問題的標題和正文相互矛盾。你想轉換爲數組還是列表? –