gpt4 book ai didi

java - 迭代映射并将其值放入 java 中

转载 作者:行者123 更新时间:2023-12-01 11:23:55 26 4
gpt4 key购买 nike

我创建了基于谷歌的 Guava 表的数据结构,如下所示

    final Table<String, String, List<String>> values = HashBasedTable.create();
values.put("ton bon", "currency", Lists.newArrayList("ccdd", "rode1", "cwey", "Certy"));
values.put("ton bon", "racy", Lists.newArrayList("wqadd", "werde", "ihtr", "ytre"));

下面是我迭代这个集合的方式

    Map<String, List<String>> fmap = new HashMap<String, List<String>>();
List<String> validColumnKeys = Arrays.asList("ccdd", "rode1", "cwey", "Certy");
Map<String, List<String>> row = values.row("ton bon");
for (String columnKey : validColumnKeys) {
fmap.put(columnKey, row.get(columnKey));
}

现在我想修改我的条件,如果行键包含 ton bon 的值,列键包含这些值 "ccdd","rode1","cwey","Certy" 那么它应该填满 map 命名为 fmap ,如下所示,第二个条件也类似。

我想要的 map :

Key        Value 
ccdd currency
rode1 currency
cwey currency
Certy currency
wqadd racy
werde racy
ihtr racy
ytre racy

但不幸的是我尝试过的代码不起作用。请告知出了什么问题以及我该如何克服这个问题。

最佳答案

它应该是列和行的循环内循环

final Table<String, String, List<String>> values = HashBasedTable.create();
values.put("ton bon", "currency", Lists.newArrayList("ccdd","rode1","cwey","Certy"));
values.put("ton bon", "racy", Lists.newArrayList("wqadd","werde","ihtr","ytre"));
Map<String, List<String>> row = values.row("ton bon");
Map<String, String> fmap = new HashMap<String, String>();
System.out.println("Key\tValue");
for(String columnKey:row.keySet()) {
List<String> rowValues = row.get(columnKey);
for(String rowValue:rowValues) {
System.out.println(rowValue + "\t" + columnKey);
fmap.put(rowValue, columnKey);
}
}

将打印

Key     Value
wqadd racy
werde racy
ihtr racy
ytre racy
ccdd currency
rode1 currency
cwey currency
Certy currency

值可以存储在fmap.put(rowValue, columnKey);.....注意:这里的键应该是唯一的

优化后的方法是

final Table<String, String, List<String>> values = HashBasedTable.create();
values.put("ton bon", "currency", Lists.newArrayList("ccdd","rode1","cwey","Certy"));
values.put("ton bon", "racy", Lists.newArrayList("wqadd","werde","ihtr","ytre"));

Collection<Map<String,List<String>>> obj = Collections2.transform(Collections2.filter(Arrays.asList(new String[]{"ton bon"}), Predicates.in(values.rowMap().keySet()) ), Functions.forMap(values.rowMap()));
System.out.println("Key\tValue");
for(Map<String,List<String>> item: obj){
for(String key: item.keySet()){
List<String> items = item.get(key);
for(String value: items){
System.out.println(value + "\t" + key);
}
}
}

关于java - 迭代映射并将其值放入 java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30979374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com