有字符串“小明,男,12,1班;小红女1,小强,男,12,2班"
将字符串分隔,保存到 Student集合中( Student类需求定义),按照年龄降序打印输出每个对象的信息。(字符串转换为整型方法:
Integervalueof(s);)

Java字符串分割,存入集合,打印内容
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 龙猫爱抓鱼 2022-11-25 17:18关注
public static void main(String[] args) { String str = "小明,男,12,1班;小红,女,14,3班;小强,男,10,2班"; String[] strArr = str.split(";"); List<Student> list = new ArrayList<>(); for (int i = 0; i < strArr.length; i++) { String[] studentArr = strArr[i].split(","); Student student = new Student(studentArr[0], studentArr[1], Integer.valueOf(studentArr[2]), studentArr[3]); list.add(student); } list.sort((s1, s2) -> s2.getAge() - s1.getAge()); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).toString()); } } //学生类定义 public class Student { private String name; private String sex; private Integer age; private String className; public Student() { } public Student(String name, String sex, Integer age, String className) { this.name = name; this.sex = sex; this.age = age; this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String toString() { return this.name + "," + this.sex + "," + this.age + "," + this.className; } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用