使用Java中的列表对象从哈希映射中提取列表

时间:2019-03-29 13:47:55

标签: java hashmap

我正在比较两个HashMap,并在第一个HashMap中提取密钥,而第二个HashMap中却没有。这是成功的。我需要提取缺少键的列表值,并且我得到了空值。我想念什么?

        ChannelsSingleBundle channelSingle = new ChannelsSingleBundle();
        //get ChannelSingle Map
        HashMap<String, List<ChannelSingle>> singleChannelsMap = channelSingle.getChannelSinglesData();
        //get Dcti map for Channels Single
        DCTIBundle dctiChannel = new DCTIBundle();
        HashMap<String, List<DCTI>> dctiChannelSingleMap = dctiChannel.getChannelSinglesData();
        //Get keys for channels hash
        HashSet<String> unionKeys = new HashSet(singleChannelsMap.keySet());
        unionKeys.addAll(dctiChannelSingleMap.keySet());
        unionKeys.removeAll(dctiChannelSingleMap.keySet());
        System.out.println("Keys in SiingleMap Not in DCTI Map: \n" + unionKeys);//Gives me the coorect keys
        List<ChannelSingle> singles = new ArrayList<>();
        for (String key : unionKeys) {
            singles =  singleChannelsMap.get(key);//Attempt to get List<ChannelSingle> from the key Pair
        }
        for(ChannelSingle single: singles){
            System.out.println(single.getHostRefNumber());
        }

编辑:如注释中所示,getHhostRefNumber确实为Null。现在的问题是,列表具有它应该具有的更多记录。我需要记录与unionKeys中的键数相等的记录。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码吗?

        ChannelsSingleBundle channelSingle = new ChannelsSingleBundle();
        //get ChannelSingle Map
        HashMap<String, List<ChannelSingle>> singleChannelsMap = channelSingle.getChannelSinglesData();
        //get Dcti map for Channels Single
        DCTIBundle dctiChannel = new DCTIBundle();
        HashMap<String, List<DCTI>> dctiChannelSingleMap = dctiChannel.getChannelSinglesData();
        //Get keys for channels hash
        HashSet<String> unionKeys = new HashSet(singleChannelsMap.keySet());

        // You do not need to add these keys
        // unionKeys.addAll(dctiChannelSingleMap.keySet());  

        unionKeys.removeAll(dctiChannelSingleMap.keySet());
        System.out.println("Keys in SiingleMap Not in DCTI Map: \n" + unionKeys);//Gives me the coorect keys
        List<ChannelSingle> singles = new ArrayList<>();
        for (String key : unionKeys) {
            singles =  singleChannelsMap.get(key);//Attempt to get List<ChannelSingle> from the key Pair

            for(ChannelSingle single: singles){
                System.out.println(single.getHostRefNumber());
            }
        }