Java 8 Convert a simple List to Map

后端 未结 1 1037
面向向阳花
面向向阳花 2021-01-24 08:22
import java.util.function.*;
import java.util.*;
public class Main
{
    public static void main(String[] args) {
        List newList = new ArrayList<         


        
1条回答
  •  感情败类
    2021-01-24 08:43

    Your map step converts a Stream to a Stream>. In order to collect that Stream to a single Map, you can write:

    Map newMap = 
        newList.stream()
               .flatMap(i->myFunc.apply(i).entrySet().stream())
               .collect(Collectors.toMap(Map.Entry::getKey, // keyMapper
                                         Map.Entry::getValue, // valueMapper
                                         (first, second) -> first,  // mergeFunction
                                         LinkedHashMap::new)); // mapFactory
    

    or

    Map newMap = 
        newList.stream()
               .map(myFunc)
               .flatMap(m->m.entrySet().stream())
               .collect(Collectors.toMap(Map.Entry::getKey, // keyMapper
                                         Map.Entry::getValue, // valueMapper
                                         (first, second) -> first,  // mergeFunction
                                         LinkedHashMap::new)); // mapFactory
    

    Of course, if all you want is to filter out the odd numbers and map the remaining numbers to "even", you can simply write:

    Map newMap = 
        newList.stream()
               .filter(i -> i % 2 == 0)
               .collect(Collectors.toMap(Function.identity(),
                                         i -> "even",
                                         (first, second) -> first,
                                         LinkedHashMap::new));
    

    0 讨论(0)
提交回复
热议问题