简体   繁体   English

如何将具有相同值的多个键插入到 Java 中的哈希映射中?

[英]How to insert multiple keys with the same value into a hash map in Java?

I am doing the following coding challenge in java:我正在用 Java 进行以下编码挑战:

/**
     * 4. Given a word, compute the scrabble score for that word.
     * 
     * --Letter Values-- Letter Value A, E, I, O, U, L, N, R, S, T = 1; D, G = 2; B,
     * C, M, P = 3; F, H, V, W, Y = 4; K = 5; J, X = 8; Q, Z = 10; Examples
     * "cabbage" should be scored as worth 14 points:
     * 
     * 3 points for C, 1 point for A, twice 3 points for B, twice 2 points for G, 1
     * point for E And to total:
     * 
     * 3 + 2*1 + 2*3 + 2 + 1 = 3 + 2 + 6 + 3 = 5 + 9 = 14
     * 
     * @param string
     * @return
     */

My idea is to insert all these letters in a hash map by doing something like this:我的想法是通过执行以下操作将所有这些字母插入哈希映射中:

map.add({A,,E,I,O,U,L,N,R,S,T}, 1);

Is there any way to do this in java?有没有办法在 Java 中做到这一点?

You said in your comments that you would like to be able to add all these entries in a single statement.您在评论中说过,您希望能够在一个语句中添加所有这些条目。 While Java is not a great language for doing things like this in a single statement, it can be done if you are really determined to do so.虽然 Java 不是一种在单个语句中执行此类操作的好语言,但如果您真的下定决心这样做,它是可以完成的。 For example:例如:

Map<Character, Integer> scores =
    Stream.of("AEIOULNRST=1","DG=2","BCMP=3","FHVWY=4" /* etc */ )
        .flatMap(line -> line.split("=")[0].chars().mapToObj(c -> new Pair<>((char)c, Integer.parseInt(line.split("=")[1]))))
        .collect(Collectors.toMap(Pair::getKey, Pair::getValue));

System.out.println("C = " + scores.get('C'));

Output:输出:

C = 3 C = 3

In the code above, I first build a stream of all the entries (as Pairs), and collect them into a map.在上面的代码中,我首先构建了一个包含所有条目(作为对)的流,并将它们收集到一个映射中。

Note:笔记:

The Pair class I have used above is from javafx.util.Pair .我在上面使用的 Pair 类来自javafx.util.Pair However you could just as easily use AbstractMap.SimpleEntry , your own Pair class, or any collection data type capable of holding two Objects.但是,您可以轻松地使用AbstractMap.SimpleEntry 、您自己的 Pair 类或任何能够容纳两个对象的集合数据类型。


A Better Approach更好的方法

Another idea would be to write your own helper method.另一个想法是编写您自己的辅助方法。 This method could be put into a class which contains similar helper methods.这个方法可以放在一个包含类似辅助方法的类中。 This approach would be more idiomatic, easier to read, and thus easier to maintain.这种方法会更惯用,更容易阅读,因此更容易维护。

public enum MapHelper {
; // Utility class for working with maps
public static <K,V> void multiKeyPut(Map<? super K,? super V> map, K[] keys, V value) {
for(K key : keys) {
    map.put(key, value);
}}}

Then you would use it like this:然后你会像这样使用它:

Map<Character, Integer> scores = new HashMap<>();
MapHelper.multiKeyPut(scores, new Character[]{'A','E','I','O','U','L','N','R','S','T'}, 1);
MapHelper.multiKeyPut(scores, new Character[]{'D','G'}, 2);
MapHelper.multiKeyPut(scores, new Character[]{'B','C','M','P'}, 3);
/* etc */

Take an array of length 26, each element representing an alphabet's score.取一个长度为 26 的数组,每个元素代表一个字母表的分数。 So, we will have an array like this:-所以,我们将有一个这样的数组:-

alphabetScore = [1,3,3,2,.....................];

Now, iterate over the word, and keep adding the score of the current alphabet in the total score.现在,遍历单词,并在总分中不断添加当前字母表的分数。

I think it's not a good idea to store list of more characters as keys (take a look at this question ) and single value corresponding to this key, but if you really need that , you might want to give a try to this:我认为将更多字符列表存储为键(看看这个问题)和与该键对应的单个值不是一个好主意,但如果你真的需要那个,你可能想尝试一下:

Map<ArrayList<Character>, Integer> map = new HashMap<>();
map.put(new ArrayList<Character>(Arrays.asList('A', 'E',...)), 1);
map.put(new ArrayList<Character>(Arrays.asList('D', 'G',...)), 2);

Personally , I would suggest using HashMap<Integer, ArrayList<Character>> - keys are "values" of a set of letters (eg key would be 1 for ArrayList containg letters: A, E, etc.), as a value corresponding to that Integer key could be ArrayList storing characters (A, E,...).个人而言,我建议使用HashMap<Integer, ArrayList<Character>> - 键是一组字母的“值”(例如,对于包含字母的ArrayList ,键为 1:A、E 等),作为对应于的值Integer 键可以是存储字符(A、E、...)的ArrayList You can achieve that result with:您可以通过以下方式实现该结果:

Map<Integer, ArrayList<Character>> map = new HashMap<>();
map.put(1, new ArrayList<Character>(Arrays.asList('A', 'E',...)));
map.put(2, new ArrayList<Character>(Arrays.asList('D', 'G',...)));

Map has no methods that operate on multiple keys, but you could stream a list of these characters and call forEach : Map没有对多个键进行操作的方法,但您可以流式传输这些字符的列表并调用forEach

Map<Character, Integer> scores = new HashMap<>();
Stream.of('A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T')
      .forEach(c -> scores.put(c, 1));
Stream.of('D', 'G').forEach(c -> scores.put(c, 2));
// etc...

One line:一条线:

Map<String, Integer> map = Stream.of( "A", "E", "I", "O", "U", "L", "N", "R", "S", "T" ).collect( Collectors.toMap( Function.identity(), o -> 1 ) );

Or if you already have a list of strings或者如果您已经有一个字符串列表

Collection<String> chars = new ArrayList<>();
// Add to collection
Map<String, Integer> map = chars.stream().collect( Collectors.toMap( Function.identity(), o -> 1 ) );

You can use the same method to add other keys with the same value您可以使用相同的方法添加具有相同值的其他键

map.addAll( Stream.of( "F", "H", "V", "W", "Y" ).collect( Collectors.toMap( FUnction.identity(), o -> 4 );

Ultimately, it would be best to use a helper function for readability最终,最好使用辅助函数来提高可读性

private Map<String, Integer> mapScores( int score, String... letter ) {
    return Stream.of( letter ).collect( Collectors.toMap( Function.identity(), o -> score ) );
}

Map<String, Integer> map = new ConcurrentHashMap<>();
map.putAll( mapScores( 1, "A", "E", "I", "O", "U", "L", "N", "R", "S", "T" ) );
map.putAll( mapScores( 2, "D", "G" ) );
map.putAll( mapScores( 3, "B", "C", "M", "P" ) );
map.putAll( mapScores( 4, "F", "H", "V", "W", "Y" ) );
map.put( "K", 5 );
map.putAll( mapScores( 8, "J", "X" ) );
map.putAll( mapScores( 10, "Q", "Z" ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM