java筛选出list中两个字段并用--连接起来返回一个新的list
假设我们有一个List,包含Person对象,每个Person对象有name和age两个字段,我们想要将name和age连接起来,返回一个新的List。
代码实现如下:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 初始化List
List<Person> personList = new ArrayList<>();
personList.add(new Person("张三", 18));
personList.add(new Person("李四", 20));
personList.add(new Person("王五", 22));
personList.add(new Person("赵六", 24));
// 筛选出name和age字段,并用--连接起来
List<String> resultList = new ArrayList<>();
for (Person person : personList) {
String nameAndAge = person.getName() + "--" + person.getAge();
resultList.add(nameAndAge);
}
// 输出结果
for (String str : resultList) {
System.out.println(str);
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
程序输出:
张三--18
李四--20
王五--22
赵六--24
在上面的代码中,我们首先初始化了一个List,包含了四个Person对象。然后,我们使用for循环遍历List中的每个Person对象,将name和age字段连接起来,存储到一个新的List中。最后,我们遍历新的List,输出结果
原文地址: https://www.cveoy.top/t/topic/huCA 著作权归作者所有。请勿转载和采集!