Java 8 新特性练习
package com.nokia.business.process.service.impl; import lombok.Data; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { Map<String, String> map = new HashMap<String,String>(); map.put("1","name"); map.put("2","name2"); map.put("3","name3"); //将map的Key加入一个list List<String> keyList = map.entrySet().stream().map(v -> v.getKey()).collect(Collectors.toList()); //System.out.println(keyList); //将map的value加入一个list List<String> valueList = map.entrySet().stream().map(v -> v.getValue()).collect(Collectors.toList()); //System.out.println(valueList); List<Employee> emps = Arrays.asList( new Employee("张三", 18, 6666.66), new Employee("李四", 20, 7777.77), new Employee("王五", 36, 8888.88), new Employee("田七", 55, 11111.11), new Employee("赵六", 55, 9999.99), new Employee("赵六", 55, 9999.99), new Employee("赵六", 45, 12222.22)); //1.过滤掉年龄小于25的员工 //emps.stream().filter((e) -> e.getAge() > 25).forEach(System.out::println); //2.过滤掉姓名重复的员工 //emps.stream().distinct().forEach(System.out::println); emps.stream().filter(distinctByKey((p) -> (p.getName()))) .collect(Collectors.toList()).forEach(System.out::println); } public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } @Data static class Employee{ private String name; private int age; private double sales; public Employee(String name, int age, double sales) { this.name = name; this.age = age; this.sales = sales; } } }
##############阁下如果是抄袭,爬取文章作恶或误导他人的开发者,请阅读中国现行法律的相关处罚条例再动手,转载之前最好先验证#############