Java 8 Convert a simple List to Map

后端 未结 1 1035
面向向阳花
面向向阳花 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<Integer> to a Stream<Map<Integer,String>>. In order to collect that Stream to a single Map, you can write:

    Map<Integer,String> 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<Integer,String> 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<Integer,String> newMap = 
        newList.stream()
               .filter(i -> i % 2 == 0)
               .collect(Collectors.toMap(Function.identity(),
                                         i -> "even",
                                         (first, second) -> first,
                                         LinkedHashMap::new));
    
    0 讨论(0)
提交回复
热议问题