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;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章