Java8中數據流的使用
阿新 • • 發佈:2017-09-25
sco nbsp ref log .get href static struct dal
Code:
@Data @ToString @NoArgsConstructor @AllArgsConstructor public class Employee { private Integer id; private Integer age; private String gender; private String firstName; private String lastName; }
Main:
public class test { public static void main(String[] args) throwsException { Employee e1 = new Employee(1, 23, "M", "Rick", "Beethovan"); Employee e2 = new Employee(2, 13, "F", "Martina", "Hengis"); Employee e3 = new Employee(3, 43, "M", "Ricky", "Martin"); Employee e4 = new Employee(4, 26, "M", "Jon", "Lowman"); Employee e5= new Employee(5, 19, "F", "Cristine", "Maria"); Employee e6 = new Employee(6, 15, "M", "David", "Feezor"); Employee e7 = new Employee(7, 68, "F", "Melissa", "Roy"); Employee e8 = new Employee(8, 79, "M", "Alex", "Gussin"); Employee e9 = new Employee(9, 15, "F", "Neetu", "Singh"); Employee e10= new Employee(10, 45, "M", "Naveen", "Jain"); List<Employee> employees = new ArrayList<Employee>(); employees.addAll(Arrays.asList(new Employee[]{e1, e2, e3, e4, e5, e6, e7, e8, e9, e10})); IntSummaryStatistics statistics = employees.stream().mapToInt(o -> o.getAge()).summaryStatistics(); System.out.println(statistics.getMax()); System.out.println(statistics.getMin()); System.out.println(statistics.getSum()); System.out.println(statistics.getAverage()); System.out.println(statistics.getCount()); //從大到小 List<Employee> list = employees.stream().sorted((a, b) -> b.getAge().compareTo(a.getAge())).limit(3).collect(Collectors.toList()); System.out.println(JSON.toJSONString(list)); val list2 = employees.stream().sorted((a, b) -> a.getFirstName().compareTo(b.getFirstName())).limit(3).collect(Collectors.toList()); System.out.println(JSON.toJSONString(list2)); } }
Output:
79 13 346 34.6 10 [{"age":79,"firstName":"Alex","gender":"M","id":8,"lastName":"Gussin"},{"age":68,"firstName":"Melissa","gender":"F","id":7,"lastName":"Roy"},{"age":45,"firstName":"Naveen","gender":"M","id":10,"lastName":"Jain"}] [{"age":79,"firstName":"Alex","gender":"M","id":8,"lastName":"Gussin"},{"age":19,"firstName":"Cristine","gender":"F","id":5,"lastName":"Maria"},{"age":15,"firstName":"David","gender":"M","id":6,"lastName":"Feezor"}]
http://www.yiibai.com/java8/java8_stream.html
Java8中數據流的使用