Java复杂的地图?

Java complex maps?

抱歉,我想不出我的问题的其他标题。我在 Java 中编写了一个程序,其中包含大量不同的变量。所以我决定使用 HashMaps(或在通用映射中)。但我对 Java 中的复杂地图知之甚少。我只知道 "HashMaps" 以及如何使用它们。这是我认为可以使用的 2 个不同的 HashMap:

public class Storage {
public static HashMap<String, Boolean> user = new HashMap<>();
public static HashMap<Integer, Double> money = new HashMap<>();
}

所以,现在有点混乱了。因此,如您所见,有 2 个 HashMap。在第一个 HashMap 中,每个键的值是 true 或 false。

public class test {
String s = "Tester";
  public void on() {
  if(Storage.user(s) == true) {
  //That part will be my question
   }
 }
}

因此,如果给定字符串的值为真,则应该有一个额外的 HashMap,就像在 Storage class 中一样。但我的意思是,每个字符串(如果它是真的)都应该有一个 HashMap 并且它们不应该共享一个 Map。 正如我所说,我对地图知之甚少,也许 HashMap 是完全错误的。如果是这样,我很抱歉。 希望你能解决我的问题并知道合适的解决方案

如果您想为每个用户创建一个单独的 Map<Integer, Double>,由 String 标识,则创建一个 Map<String, Map<Integer, Double>>

您不需要 Boolean 的映射,因为您可以使用 containsKey() 检查用户是否存在,或者简单地获取外部映射的值并检查 null.

class Storage {
    public static Map<String, Map<Integer, Double>> user = new HashMap<>();
}
Map<Integer, Double> money = Storage.map.get(userName);
if (money != null) {
    // code here
}

更新

构建地图时,使用 computeIfAbsent() and merge() 方法,如下所示:

class Storage {
    public static Map<String, Map<Integer, Double>> user = new HashMap<>();

    public static void addUserMoney(String userName, int moneyKey, double amount) {
        user.computeIfAbsent(userName, k -> new HashMap<>())
            .merge(moneyKey, amount, Double::sum);
    }
}

测试

Storage.addUserMoney("John", 1, 9.95);
Storage.addUserMoney("Jane", 3, 3.75);
Storage.addUserMoney("John", 1, 4.25);
System.out.println(Storage.user);

输出

{John={1=14.2}, Jane={3=3.75}}

你需要的是地图中的地图。

Map<String, Map<Integer,Double>> map = new HashMap<>();

然后您可以将值为 true 的字符串放在那里。

示例:

Map<String, Map<Integer,Double>> map = new HashMap<>();

以下:

Map.computeIfAbsent(Key, (a)->new HashMap<>()).put(i, d);

行为方式与

相同
Map<Integer,Double> innerMap = map.get(Key);
if (innerMap == null) {
     innerMap = new HashMap<>();
     map.put(Key, innerMap)
}
innerMap.put(i, d);

分配一些值


map.computeIfAbsent("A", (a)->new HashMap<>()).put(10,20.56);
map.computeIfAbsent("A", (a)->new HashMap<>()).put(20,4.2);
map.computeIfAbsent("A", (a)->new HashMap<>()).put(30,10.6);

map.computeIfAbsent("B", (a)->new HashMap<>()).put(1,2.);
map.computeIfAbsent("B", (a)->new HashMap<>()).put(2,2.44);
map.computeIfAbsent("B", (a)->new HashMap<>()).put(10,2.45);

map.computeIfAbsent("C", (a)->new HashMap<>()).put(30,3.2);

打印所有值

map.entrySet().forEach(System.out::println);

获取特定值

double d = map.get("A").get(10); // gets 20.56 from Map "A"
System.out.println(d); 

如果您已经知道内部映射与键相关联,您可以执行以下操作:

// gets the map at "C"
// and puts 44.7 at key 44
map.get("C").put(44,44.7);