我有一个类EmpObj
,它有两个参数Integer Empid
和BigDecimal Salary
。我有一张结构为Map<String, List<EmpObj>> map
的地图我希望我的结果在过滤工资> 25000 的所有员工后采用地图格式Map<String, List<Integer>>
。最终列表将包含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]我的问题解决了。
好吧,您无法将BigDecimal
与通常的>
和<
进行比较,您可以做的是创建一个变量BigDecimal compareAgainst = BigDecimal.valueOf(25000L)
并将其与过滤器语句一起使用:
...filter(entry -> entry.getValue().getSalary().compareTo(compareAgainst) > 0)
我会让你弄清楚在这种情况下compareTo
是如何工作的;过滤后,你不需要将它们收集回Map
简单地打印,例如:
.forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue().getEmpid()))
构建这个解决方案取决于你,因为你说你是一个乞丐;反正它并不复杂。
由于您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);