Java 8新特性之集合
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { Grade grade = new Grade(); grade.name = "三年级一班"; List<Students> sList = new ArrayList<>();//熟知的钻石语法 for(int i = 0;i < 10;i++){ Students temp = new Students(); temp.name = "王"+i; temp.age = i; temp.grade= grade; sList.add(temp); } List<Map<String, Object>> data = sList.stream() .map(student->{ Map<String,Object> map = new TreeMap<String, Object>(); map.put("姓名:", student.name); map.put("年龄:", student.age); map.put("所在班级:", student.grade.name); return map; }).collect(Collectors.toList()); for(int i =0;i<data.size();i++) { Map<String, Object> map = data.get(i); System.out.print(map.get("姓名:")+" "); System.out.print(map.get("年龄:")+" "); System.out.print(map.get("所在班级:")+"\n"); } } } class Students{ public String name; public Integer age; public Grade grade; } class Grade{ public String name; }
本人新手,写随笔只是记录成长过程,对大家有帮助的地方,可以采纳,写的不好的地方也可以批评指正,谢谢!