Remember the problems in converting List to map (java)

Java 8 uses the List of stream to map the problems encountered.
Let's start with a brief introduction to the new feature of Java8, Lambda expression. In a word, it is an anonymous class function or closure. The advantage is that it can dynamically operate the data structure we need to operate. In normal development, List to Map is often used, for example:

    public static void main(String\[\] arg){  
        List<Test> testList = new ArrayList<>();  
        Map<Integer, Test> testMap = testList.stream().collect(Collectors.toMap(Test::getId, test -> test));  
    }

    [@Data](https://my.oschina.net/difrik)  
    private static class Test {  
        private Integer id;  
        private String name;  
    }  

I created a Test object to convert the collection of Test objects into a map. But logically, there is no problem.
But after the test, we will find something wrong. Let's add several sets of data to test.

    public static void main(String\[\] arg){  
        List<Test> testList = new ArrayList<>();  
        testList.add(new Test(1, "test"));  
        testList.add(new Test(2, "test"));  
        testList.add(new Test(3, "test"));  
        testList.add(new Test(1, "test"));  
        Map<Integer, Test> testMap = testList.stream().collect(Collectors.toMap(Test::getId, test -> test));  
    }

    [@Data](https://my.oschina.net/difrik)  
    @AllArgsConstructor  
    private static class Test {  
        private Integer id;  
        private String name;  
    }  

Compilation found that a typical error would occur.

Exception in thread "main" java.lang.IllegalStateException: Duplicate key FtpUtil.Test(id=1, name=test)  

The exception is very clear, that is, there are duplicate key values during map transformation, so such an exception needs to be solved.
Direct code:

        Map<Integer, Test> testMap = testList.stream().collect(Collectors.toMap(Test::getId, Function.identity(),   
                (test1, test2) -> test1));  
    /**  
     \* Returns a function that always returns its input argument.  
     *  
     \* [@param](https://my.oschina.net/u/2303379) <T> the type of the input and output objects to the function  
     \* [@return](https://my.oschina.net/u/556800) a function that always returns its input argument  
     */  
    static <T> Function<T, T> identity() {  
        return t -> t;  
    }  

We use the Function interface. The official instructions are very clear. It returns a required data.

Tags: Programming Java Lambda

Posted on Thu, 19 Mar 2020 07:55:27 -0700 by frontlines