Java 8 List into Map

前端 未结 22 2719
半阙折子戏
半阙折子戏 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:24

    I will write how to convert list to map using generics and inversion of control. Just universal method!

    Maybe we have list of Integers or list of objects. So the question is the following: what should be key of the map?

    create interface

    public interface KeyFinder {
        K getKey(E e);
    }
    

    now using inversion of control:

      static  Map listToMap(List list, KeyFinder finder) {
            return  list.stream().collect(Collectors.toMap(e -> finder.getKey(e) , e -> e));
        }
    

    For example, if we have objects of book , this class is to choose key for the map

    public class BookKeyFinder implements KeyFinder {
        @Override
        public Long getKey(Book e) {
            return e.getPrice()
        }
    }
    

提交回复
热议问题