首页 > 编程语言 > Java Lambda List转Map代码实例
2020
09-24

Java Lambda List转Map代码实例

在有些开发场景,需要对 List 对象列表进行过滤处理,并将有用的数据存放到Map中。

例如:告警对象,包含告警uuid(alarmUuid) 和 设备uuid(objUuid),需要对 objUuid = -1的告警进行过滤,并将过滤后告警数据的alarmUuid和 objUuid以键值对的形式保存到Map中。

1、告警对象定义如下:

/**
 * Created by Miracle Luna on 2020/3/16
 */
public class AlarmInfoResponse {
  private String alarmUuid;
  private String objUuid;

  public AlarmInfoResponse(String alarmUuid, String objUuid) {
    this.alarmUuid = alarmUuid;
    this.objUuid = objUuid;
  }

  public String getAlarmUuid() {
    return alarmUuid;
  }

  public void setAlarmUuid(String alarmUuid) {
    this.alarmUuid = alarmUuid;
  }

  public String getObjUuid() {
    return objUuid;
  }

  public void setObjUuid(String objUuid) {
    this.objUuid = objUuid;
  }

  @Override
  public String toString() {
    return "AlarmInfoResponse{" +
        "alarmUuid='" + alarmUuid + '\'' +
        ", objUuid='" + objUuid + '\'' +
        '}';
  }
}

2、过滤代码如下:

/**
 * Created by Miracle Luna on 2020/3/16
 */
public class LambdaFilterListToMap {

  public static void main(String[] args) {
    List<AlarmInfoResponse> alarmInfoResponseList = new ArrayList<>();
    AlarmInfoResponse response0 = new AlarmInfoResponse("alarm0", "-1");
    AlarmInfoResponse response1 = new AlarmInfoResponse("alarm1", "1");
    AlarmInfoResponse response2 = new AlarmInfoResponse("alarm2", "2");
    AlarmInfoResponse response3 = new AlarmInfoResponse("alarm3", "3");
    alarmInfoResponseList.add(response0);
    alarmInfoResponseList.add(response1);
    alarmInfoResponseList.add(response2);
    alarmInfoResponseList.add(response3);

    // 方式1:先使用foreach遍历(遍历过程中条件判断)
    Map<String, String> alarmObjUuidMap1 = new HashMap<>();
    alarmInfoResponseList.forEach(alarmInfoResponse -> {
      if(!"-1".equals(alarmInfoResponse.getObjUuid())) {
        alarmObjUuidMap1.put(alarmInfoResponse.getAlarmUuid(), alarmInfoResponse.getObjUuid());
      }
    });
    System.out.println("============= 方式1 ====================");
    alarmObjUuidMap1.forEach((alarmUuid, objUuid) -> System.out.println(alarmUuid + " : " + objUuid));


    // 方式2:使用流过滤,再使用foreach遍历
    Map<String, String> alarmObjUuidMap2 = new HashMap<>();
    alarmInfoResponseList.stream().
    filter(alarmInfoResponse -> !"-1".equals(alarmInfoResponse.getObjUuid())).
    forEach(alarmInfoResponse -> alarmObjUuidMap2.put(alarmInfoResponse.getAlarmUuid(), alarmInfoResponse.getObjUuid()));
    System.out.println("\n============= 方式2 ====================");
    alarmObjUuidMap2.forEach((alarmUuid, objUuid) -> System.out.println(alarmUuid + " : " + objUuid));
  }
}

3、运行结果如下:

============= 方式1 ====================
alarm2 : 2
alarm1 : 1
alarm3 : 3

============= 方式2 ====================
alarm2 : 2
alarm1 : 1
alarm3 : 3

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧