zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }
  • 相关阅读:
    【LeetCode-栈】栈排序
    【LeetCode-数组】旋转数组
    【LeetCode-数组】两个数组的交集 II
    【LeetCode-树】二叉树的层次遍历 II
    【LeetCode-字符串】Fizz Buzz
    【LeetCode-数组】数组的相对排序
    解决Oracle表中数据乱码的问题
    docker搭建mysql 用户名密码忘记了怎么办
    java中如何将string 转化成long
    http三次握手四次挥手
  • 原文地址:https://www.cnblogs.com/chuyuan/p/13306783.html
Copyright © 2011-2022 走看看