Java 8 List into Map

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

    Most of the answers listed, miss a case when the list has duplicate items. In that case there answer will throw IllegalStateException. Refer the below code to handle list duplicates as well:

    public Map<String, Choice> convertListToMap(List<Choice> choices) {
        return choices.stream()
            .collect(Collectors.toMap(Choice::getName, choice -> choice,
                (oldValue, newValue) -> newValue));
      }
    
    0 讨论(0)
  • 2020-11-22 04:20
    String array[] = {"ASDFASDFASDF","AA", "BBB", "CCCC", "DD", "EEDDDAD"};
        List<String> list = Arrays.asList(array);
        Map<Integer, String> map = list.stream()
                .collect(Collectors.toMap(s -> s.length(), s -> s, (x, y) -> {
                    System.out.println("Dublicate key" + x);
                    return x;
                },()-> new TreeMap<>((s1,s2)->s2.compareTo(s1))));
        System.out.println(map);
    

    Dublicate key AA {12=ASDFASDFASDF, 7=EEDDDAD, 4=CCCC, 3=BBB, 2=AA}

    0 讨论(0)
  • 2020-11-22 04:23

    It's possible to use streams to do this. To remove the need to explicitly use Collectors, it's possible to import toMap statically (as recommended by Effective Java, third edition).

    import static java.util.stream.Collectors.toMap;
    
    private static Map<String, Choice> nameMap(List<Choice> choices) {
        return choices.stream().collect(toMap(Choice::getName, it -> it));
    }
    
    0 讨论(0)
  • 2020-11-22 04:23
    Map<String,Choice> map=list.stream().collect(Collectors.toMap(Choice::getName, s->s));
    

    Even serves this purpose for me,

    Map<String,Choice> map=  list1.stream().collect(()-> new HashMap<String,Choice>(), 
                (r,s) -> r.put(s.getString(),s),(r,s) -> r.putAll(s));
    
    0 讨论(0)
  • 2020-11-22 04:23
    List<V> choices; // your list
    Map<K,V> result = choices.stream().collect(Collectors.toMap(choice::getKey(),choice));
    //assuming class "V" has a method to get the key, this method must handle case of duplicates too and provide a unique key.
    
    0 讨论(0)
  • 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, E> {
        K getKey(E e);
    }
    

    now using inversion of control:

      static <K, E> Map<K, E> listToMap(List<E> list, KeyFinder<K, E> 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<Long, Book> {
        @Override
        public Long getKey(Book e) {
            return e.getPrice()
        }
    }
    
    0 讨论(0)
提交回复
热议问题