简体   繁体   English

使用 Java 8 模式匹配将 Map 转换为 List

[英]Convert Map to List using Java 8 Pattern matching

I have a requirement to store those employees key matching Address1 to a new List<EmpData> , code is given below, I am able to do it by normal iterations.我需要将那些与List<EmpData>匹配的员工密钥存储到新的List<EmpData> ,代码如下,我可以通过正常迭代来完成。

Can I do it with java8 pattern matching using collect and filter etc.?我可以使用collectfilter等使用 java8 模式匹配来完成吗?

public static void main(String[] args) {
    List<EmpData> lst1 = new ArrayList<EmpData>();
    List<EmpData> lst2 = new ArrayList<EmpData>();
    EmpData obj1=new EmpData("100", "Name1", "25/05/1979");
    EmpData obj2=new EmpData("101", "Name2", "25/05/1975");
    EmpData obj3=new EmpData("103", "Name3", "25/05/1976");
    lst1.add(obj1);
    lst1.add(obj2);
    lst2.add(obj3);

    HashMap<String, List<EmpData>> map = new HashMap<>();

    map.put("Address1Emp1", lst1);
    map.put("Address2Emp2", lst2);

    List<EmpData> listEmp = new ArrayList<>();
    //Need to store those employees key matching Address1 to a List<EmpData>

}

I'm guessing you meant streams from java-8 and the requirement, that the key must match "Address1Emp.*" regex.我猜你的意思是来自 java-8 的流和要求,即键必须匹配"Address1Emp.*"正则表达式。

You can use the following code:您可以使用以下代码:

map.entrySet().stream() // create a stream of entries
    .filter(e -> e.getKey().matches("Address1Emp.*")) // leave only those entries, whose keys start with "Address1"
    .map(Map.Entry::getValue) // get values only
    .collect(Collectors.toList()); 

Edit after you have added the inner lists:添加内部列表后进行编辑:

map.entrySet().stream() // create a stream of entries
    .filter(e -> e.getKey().matches("Address1Emp.*")) // leave only those entries, whose keys start with "Address1"
    .flatMap(e -> e.getValue().stream()) // get values only
    .collect(Collectors.toList()); 

Depending on which pattern you need you can use startsWith根据您需要的模式,您可以使用startsWith

List<EmpData> listEmp = map.entrySet().stream()
    .filter(e -> e.getKey().startsWith("Address1"))
    .map(Entry::getValue)
    .collect(Collectors.toList());

or with contains :contains

List<EmpData> listEmp = map.entrySet().stream()
    .filter(e -> e.getKey().contains("Address1"))
    .map(Entry::getValue)
    .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM