簡體   English   中英

過濾地圖 <String,List<Object> &gt;到地圖 <String,Integer>

[英]Filtering Map<String,List<Object>> to Map<String,Integer>

我有一個Class EmpObj ,它有兩個參數Integer EmpidBigDecimal Salary 我有一個Map的結構Map<String, List<EmpObj>> map我想我的結果是格式Map<String, List<Integer>> map過濾所有員工的工資> 25000.最終的List將包含Name(String)Integer(EmpID)

到目前為止我的方法:

public  class EmpObj {
    Integer empid;
    BigDecimal salary;`


    public EmpObj(Integer empid, BigDecimal salary) {
        this.empid = empid;
        this.salary = salary;
    }}

public static void main(String[] args) {
        Map<String, List<EmpObj>> map = new HashMap<>();
        EmpObj e1= new EmpObj(12,new BigDecimal(23000));
        EmpObj e2= new EmpObj(13,new BigDecimal(45000));
        EmpObj e3= new EmpObj(14,new BigDecimal(65000));
        List<EmpObj> o1 = new ArrayList<>();
        o1.add(e1);
        map.put("Vinny",o1);
        List<EmpObj> o2 = new ArrayList<>();
        o2.add(e2);
        map.put("David",o2);
        List<EmpObj> o3 = new ArrayList<>();
        o3.add(e3);
        map.put("Mike",o3);

我的Java-8表達式:

Map<String,List<EmpObj>> Mp1 =
            map.entrySet().stream()
                .filter(s->//Something Here)
                .collect(Collectors.toMap(Map.Entry::getKey,
                    Map.Entry::getValue));
         Mp1.entrySet().stream().forEach(System.out::println);

我沒有得到結果,有什么建議嗎?

我的輸出需要是大衛= [14],邁克= [13]我的問題解決了。

由於您將List<EmpObj>作為地圖值,因此需要將1級降低EmpObj以過濾所有工資。 同時你仍然需要保留地圖的鍵,因為你想在最后打印它。

您可以使用flatMap並在SimpleEntry保存鍵和值,如:

Map<String, List<Integer>> collect = map.entrySet().stream()
        .flatMap(entry -> entry.getValue().stream()
                .filter(empObj -> empObj.getSalary().compareTo(new BigDecimal(25000)) > 0)
                .map(empObj -> new AbstractMap.SimpleEntry<>(entry.getKey(), empObj)))
        .collect(groupingBy(Map.Entry::getKey, 
                 mapping(entry -> entry.getValue().getEmpid(), toList())));

System.out.println(collect);

好吧,你無法將BigDecimal與通常的><進行比較,你可以做的是創建一個變量BigDecimal compareAgainst = BigDecimal.valueOf(25000L)並將其與你的filter語句一起使用:

...filter(entry -> entry.getValue().getSalary().compareTo(compareAgainst) > 0)

我會告訴你在這種情況下compareTo是如何工作的; 一旦過濾,您不需要將它們收回到Map只是為了打印,例如:

.forEach(entry -> System.out.println(entry.getKey() + "  " +  entry.getValue().getEmpid()))

建立這個解決方案取決於你,因為你說你是一個初學者; 反正它並不復雜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM