jdk1.8比之前的1.7/1/6/1/5增加了不少新特性
1.stream().map() 将对象转换成另一个对象
@Test public void text1() { List<Staff> staff = Arrays.asList( new Staff("mkyong", 30, new BigDecimal(10000)), new Staff("jack", 27, new BigDecimal(20000)), new Staff("lawrence", 33, new BigDecimal(30000)) ); // convert inside the map() method directly. List<StaffPublic> result = staff.stream().map(temp -> { StaffPublic obj = new StaffPublic(); obj.setName(temp.getName()); obj.setAge(temp.getAge()); if ("mkyong".equals(temp.getName())) { obj.setExtra("this field is for mkyong only!"); } return obj; }).collect(Collectors.toList()); System.out.println("1:"+result); }
public class Staff { private String name; private int age; private BigDecimal salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } public Staff(String name, int age, BigDecimal salary) { super(); this.name = name; this.age = age; this.salary = salary; } @Override public String toString() { return "Staff [name=" + name + ", age=" + age + ", salary=" + salary + "]"; } }
public class StaffPublic { private String name; private int age; private String extra; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public StaffPublic() { super(); // TODO Auto-generated constructor stub } public StaffPublic(String name, int age, String extra) { super(); this.name = name; this.age = age; this.extra = extra; } }
反馈结果:
1:[zjjysjz2019_model.StaffPublic@7f77e91b, zjjysjz2019_model.StaffPublic@44a664f2, zjjysjz2019_model.StaffPublic@7f9fcf7f]
2 Streams Collectors groupingBy 进行分组,并显示每组的个数
@Test public void text2() { //3 apple, 2 banana, others 1 List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya"); Map<String, Long> result =items .stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(result); Map<String, Long> finalMap = new LinkedHashMap<>(); //reversed 反排序 result.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue() .reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue())); System.out.println(finalMap); }
反馈结果:
{papaya=1, orange=1, banana=2, apple=3}
{apple=3, banana=2, papaya=1, orange=1}