本文共 3624 字,大约阅读时间需要 12 分钟。
最近在公司的项目中常用Stream结合Lambda表达式来操作集合,使得项目整体代码简洁和整齐;并且上一章也讲了一些关于Stream的常用操作,比如:map()、filter()、concat()、reduce()、max()、min()、distinct()等常用操作。这篇我就分享一下Stream中List、Set、Map之间的转换操作:
准备工作:新建一个Course类,包含name、credit两个属性,并重写hashCode()、equals()方法:
class Course { private String name; private Integer credit; public Course(String name, Integer credit) { this.name = name; this.credit = credit; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCredit() { return credit; } public void setCredit(Integer credit) { this.credit = credit; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { Course stu = null; if (obj != null && obj instanceof Course) { stu = (Course) obj; if (this.name.equals(stu.getName()) && this.credit.equals(stu.getCredit())) { return true; } } return false; }}
/** * Stream将List转换为Map集合 */@Testpublic void listToMap() { ListstuList = Arrays.asList( new Course("Android", 10), new Course("Java", 8), new Course("Structure", 13), new Course("IOS", 12), new Course("Guava", 16), new Course("OS", 6)); Map nameAgeMap = stuList.stream(). collect(Collectors.toMap(Course::getName, Course::getCredit)); nameAgeMap.entrySet().stream().forEach(x -> System.out.println(x.getKey() + ", " + x.getValue())); //Function.identity()指代本身,相当于 x -> x Map nameStuMap = stuList.stream(). collect(Collectors.toMap(Course::getName, Function.identity())); nameStuMap.entrySet().stream().forEach(x -> System.out.println(x.getKey() + "," + x.getValue().getCredit()));}
执行结果展示:(两次结果展示一致)
Guava, 16
Java, 8 OS, 6 IOS, 12 Structure, 13 Android, 10注意:collect(Collectors.toMap(Course::getName,Function.identity())) 得到的是<name,course>Map集合。
查看Function.identity()底层实现原理:t -> t 返回对象本身
staticFunction identity() { return t -> t;}
@Test public void listToSet() { ListintegerList = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5); Set integerSet = integerList.stream(). collect(Collectors.toSet()); integerSet.stream().forEach(System.out::print); System.out.println(""); List courseList = Arrays.asList( new Course("Android", 10), new Course("Java", 8), new Course("Android", 10), new Course("IOS", 12), new Course("Guava", 16), new Course("Android", 6)); //排序并去重 List courList = courseList.stream(). sorted(Comparator.comparing(Course::getName)). distinct(). collect(Collectors.toList()); courList.stream().forEach(c -> System.out.println(c.getName() + "," + c.getCredit())); //只去重Set Set courSet = courseList.stream(). sorted(Comparator.comparing(Course::getName)). collect(Collectors.toSet()); courSet.stream().forEach(c -> System.out.println(c.getName() + "," + c.getCredit())); }
结果展示:
12345
Android,10 Android,6 Guava,16 IOS,12 Java,8 Guava,16 Java,8 IOS,12 Android,10 Android,6注意:对象去重需要重写类的hashCode()、equals()方法,给出去重排序、去重的List转换为Set集合。
Stream操作集合的功能十分强大,结合Lambda表达式使得代码简洁大方、便捷,还有很多StreamAPI需要讨论,后续待学希望一起讨论进步......
转载地址:http://ncxxi.baihongyu.com/