java arraymap,如何在Java中交换arrayMap值和键

I'm having a bit of trouble reversing a given map and storing its reversed keys and values into another map. I have a method prototype as follows:

public static Map> reverse (Map > graph);

So if I have sample keys for the directed graph such that:

{c -> arraySet{f, e}}

{b -> d}

{a -> arraySet{c, b}}

{d -> g}

{e -> d}

{f -> arraySet{g, d}}

I need to effectively reverse this graph so that instead of b -> d I have d -> b.

I think all this requires is for me is to interchange the values and keys in the original graph and add them to the reverseMap. I suppose I could iterate through each set of values for a given key in the graph and then and store those in a list.

Unfortunately, I'm having trouble implementing this and thinking it through. I'd really appreciate a nudge in the right direction.

解决方案

You will need to loop over the entries in your map, and then, since the values are stored in a set, you will need to loop over that set. You will need to check your result map for each key and create a new set whenever a key does not yet exist.

public static Map> reverse (Map > graph) {

Map> result = new HashMap>();

for (Map.Entry> graphEntry: graph.entrySet()) {

for (String graphValue: graphEntry.getValue()) {

Set set = result.get(graphValue);

if (set == null) {

set = new HashSet();

result.put(graphValue, set);

}

set.add(graphEntry.getKey());

}

}

return result;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值