Java 8 – Convert Map to List

Few Java examples to convert a Map to a List

Map<String, String> map = new HashMap<>();

// Convert all Map keys to a List
List<String> result = new ArrayList(map.keySet());

// Convert all Map values to a List
List<String> result2 = new ArrayList(map.values());

// Java 8, Convert all Map keys to a List
List<String> result3 = map.keySet().stream().collect(Collectors.toList());

// Java 8, Convert all Map values  to a List
List<String> result4 = map.values().stream().collect(Collectors.toList());

// Java 8, seem a bit long, but you can enjoy the Stream features like filter and etc.
List<String> result5 = map.values().stream()
    .filter(x -> !"apple".equalsIgnoreCase(x))
    .collect(Collectors.toList());
package com.sheting.java8;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ConvertMapToList {
    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(10, "apple");
        map.put(20, "orange");
        map.put(30, "banana");
        map.put(40, "watermelon");
        map.put(50, "dragonfruit");

        // split a map into 2 List
        List<Integer> resultSortedKey = new ArrayList<>();
        List<String> resultValues = map.entrySet().stream()
                // sort a Map by key and stored in resultSortedKey
                .sorted(Map.Entry.<Integer, String>comparingByKey().reversed()).peek(e -> resultSortedKey.add(e.getKey())).map(x -> x.getValue())
                // filter banana and return it to resultValues
                .filter(x -> !"banana".equalsIgnoreCase(x)).collect(Collectors.toList());

        resultSortedKey.forEach(System.out::println); // 50 40 30 20 10
        resultValues.forEach(System.out::println); // dragonfruit watermelon orange apple
    }
}
    原文作者:Java-Money
    原文地址: https://blog.csdn.net/tb9125256/article/details/81161402
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞