Java 8 List into Map

前端 未结 22 2746
半阙折子戏
半阙折子戏 2020-11-22 03:38

I want to translate a List of objects into a Map using Java 8\'s streams and lambdas.

This is how I would write it in Java 7 and below.

private Map&l         


        
22条回答
  •  故里飘歌
    2020-11-22 04:25

    I was trying to do this and found that, using the answers above, when using Functions.identity() for the key to the Map, then I had issues with using a local method like this::localMethodName to actually work because of typing issues.

    Functions.identity() actually does something to the typing in this case so the method would only work by returning Object and accepting a param of Object

    To solve this, I ended up ditching Functions.identity() and using s->s instead.

    So my code, in my case to list all directories inside a directory, and for each one use the name of the directory as the key to the map and then call a method with the directory name and return a collection of items, looks like:

    Map> items = Arrays.stream(itemFilesDir.listFiles(File::isDirectory))
    .map(File::getName)
    .collect(Collectors.toMap(s->s, this::retrieveBrandItems));
    

提交回复
热议问题