当前位置: 首页 > 知识库问答 >
问题:

将地图值转换为另一个地图对象

卢鸿博
2023-03-14

我有一张这样的地图<代码>地图

钥匙是数字1,2,3,4。。。学生对象是:

public class Student {
 private long addressNo;
 private String code;
 private BigDecimal tax;
 private String name;
 private String city;

 // getter and setters` 
}

我想做的是把它转换成地图

我可以使用这些代码对地图进行分组,但summingDouble不适用于BigDecimal。此外,我无法将我的studentMap转换为StudentInfo地图:(

 studentInfoMap.values().stream()
            .collect(
                     Collectors.groupingBy(StudentInfo::getCode, 
                     Collectors.groupingBy(StudentInfo::getAddressNo, 
                     Collectors.summingDouble(StudentInfo::getTax))));

我的学生信息对象是:

public class StudentInfo {
  private long addressNo;
  private String code;
  private BigDecimal tax;

  // getter and setters` 
}

共有1个答案

邰钟展
2023-03-14

转换地图

Map<Long,List<StudentInfo>> convertedMap = 
  studentInfoMap.entrySet() //get the entry set to access keys and values
    .stream() 
    .collect(Collectors.toMap( //collect the entries into another map
        entry -> entry.getKey(), //use the keys as they are
        entry -> entry.getValue() //get the value list
                      .stream() /
                      .map(student -> new StudentInfo(/*pass in the student parameters you need*/) //create a StudentInfo out of a Student - and entry.getKey() if needed
                      .toList() //collect the StudentInfo elements into a list
     ));

减少列表

创建一个key类

如果你想折叠/减少一个List

class StudentAddressKey {
  private long addressNo;
  private String code;

  //getters, setters, equals() and hashCode()
}

然后你可以考虑在Student中使用这个键,而不是单独的键,但这是另一个主题。

传统回路

然后归结到用这个键求和税收价值。使用传统的for循环,它可能会如下所示:

Map<StudentAddressKey, BigDecimal> taxByKey = new HashMap<>();

for( Student student : studentList) {
  taxByKey.merge(student.getAddressKey(), //or build a new one from the individual attributes
                 student.getTax(), //the value to merge into the map
                 BigDecimal::add ); //called if there's already a value in the map, could also be (e,n) -> e.add(n)
}

如果你想要一个Map

  • 为每个想要添加的学生创建一个,将其传递到merge(),如果已经有一个,则将新的和现有的组合起来

获取列表

  • 如果你有一张地图

流动

使用上面的信息,您还可以使用流转换List

Map<StudentAddressKey, BigDecimal> taxesMap = studentList.stream()
  .collect( 
     Collectors.groupingBy( student -> new StudentAddressKey(student), //create the key to group by
        Collectors.mapping( student -> student.getTax()), //map the student to its tax value
          Collectors.reducing( BigDecimal.ZERO, BigDecimal::add) //reduce the mapped tax values by adding them, starting with 0 (otherwise you'd get an Optional<BigDecimal>
        )
      )
    );

注意:你也可以直接将Student映射到StudentInfo,但是合并它们会更复杂,因为你只需要一个BigDecimal我会选择更简单的选项。

现在使用上述方法将taxesMap转换为列表

List<StudentInto> taxesList = taxesMap.entrySet().stream()
                .map( entry -> new StudentInfo(entry.getKey(), entry.getValue)) //map the entry to StudentInfo, provide the necessary constructor or adapt as needed
                .toList();

 类似资料: