从hashtable获取值,其中key是ArrayList <string>,lookup是String

时间:2018-05-19 22:14:04

标签: java string arraylist hashtable

我去发送一个字符串哈希表,并检查它的键(这是ArrayList)。如果ArrayList包含给定的String,则返回键的值。

package com;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;

public class TestMain {
    private static final String str1 = "n";
    private static final String str2 = "north";
    private static final Hashtable<ArrayList<String>,String> compassDirection = new Hashtable<ArrayList<String>,String>() {{
        put(new ArrayList<>(Arrays.asList("n", "north")), "North");
        put(new ArrayList<>(Arrays.asList("s", "south")), "South");
        put(new ArrayList<>(Arrays.asList("e", "east")), "East");
        put(new ArrayList<>(Arrays.asList("w", "west")), "West");
    }};

    public static void main(String[] args) {
        // print str1 as "North" from hashtable call
        // print str2 as "North" from hashtable call
    }
}

2 个答案:

答案 0 :(得分:0)

我想我现在使用的解决方法如下......

package com;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;

public class TestMain {
    private static final String str1 = "n";
    private static final String str2 = "north";
    private static final Hashtable<String,String> compassDirection = new Hashtable<String,String>() {{
        put("n", "North");
        put("north", "North");
        put("s", "South");
        put("south", "South");
        put("e", "East");
        put("east", "East");
        put("w", "West");
        put("west", "West");
    }};

    public static void main(String[] args) {
        System.out.println(compassDirection.get(str1));
        System.out.println(compassDirection.get(str2));
    }
}

但是知道使用ArrayList的问题是否可行仍然很好。

答案 1 :(得分:0)

使用Guava的Multimap。您可以使用key =“North”和值[“n”,“north”]填充它。然后在Multimap上调用invert,它会为您提供另一个key =“n”的映射,其值为[“North”],key =“north”且值为[“North”]。这使您可以使用所需的格式输入值,然后从该地图生成一个允许您按照自己的意愿进行查找的地图。

或者输入与上述类似的值,但使用

 Map<String, List<String>>

并编写自己的反转方法,返回

Map<String, String>.