Java List以key为键生成Map小🌰

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Jasonote
 * @Date: 2017/12/20
 **/
public class TestDemo {


    public static void main(String[] args) {
        List<ProcurementOrderInstockDTO> poiInstockData = new ArrayList<>();

        ProcurementOrderInstockDTO procurementOrderItemDTO = new ProcurementOrderInstockDTO();
        procurementOrderItemDTO.setId(1L);
        procurementOrderItemDTO.setPoi(111L);
        procurementOrderItemDTO.setWeight(88L);
        poiInstockData.add(procurementOrderItemDTO);

        ProcurementOrderInstockDTO procurementOrderItemDTO2 = new ProcurementOrderInstockDTO();
        procurementOrderItemDTO2.setId(2L);
        procurementOrderItemDTO2.setPoi(111L);
        procurementOrderItemDTO2.setWeight(99L);
        poiInstockData.add(procurementOrderItemDTO2);

        Map<Long, List<ProcurementOrderInstockDTO>> instockDataListMap = new HashMap<>();
        for (ProcurementOrderInstockDTO procurementOrderInstockDTO1 : poiInstockData) {
            if (instockDataListMap.containsKey(procurementOrderInstockDTO1.getPoi())) {
                instockDataListMap.get(procurementOrderInstockDTO1.getPoi()).add(procurementOrderInstockDTO1);
            } else {
                List<ProcurementOrderInstockDTO> instockDTOList = new ArrayList<>();
                instockDTOList.add(procurementOrderInstockDTO1);
                instockDataListMap.put(procurementOrderInstockDTO1.getPoi(), instockDTOList);
            }
        }

        System.out.println("instockDataListMap = " + instockDataListMap);
    }
}

class ProcurementOrderInstockDTO {
    private Long id;
    private Long poi;
    private Long weight;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getPoi() {
        return poi;
    }

    public void setPoi(Long poi) {
        this.poi = poi;
    }

    public Long getWeight() {
        return weight;
    }

    public void setWeight(Long weight) {
        this.weight = weight;
    }
}

Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...