简体   繁体   English

用Java映射两个字符串数组

[英]Mapping Two String Arrays in Java

I'm trying to find out if there is an easier way to map two string arrays in Java . 我试图找出是否有一种更简单的方法来映射Java中的两个字符串数组。 I know in Python , it's pretty easy in two lines code. 我知道在Python中 ,用两行代码很容易。 However, i'm not sure if Java provides an easier option than looping through both string arrays. 但是,我不确定Java是否提供比遍历两个字符串数组更简单的选项。

String [] words  = {"cat","dog", "rat", "pet", "bat"};

String [] numbers  = {"1","2", "3", "4", "5"};

My goal is the string "1" from numbers to be associated with the string "cat" from words, the string "2" associated with the string "dog" and so on. 我的目标是将数字中的字符串“ 1”与单词中的字符串“ cat”相关联,将字符串“ 2”与字符串“ dog”相关联,依此类推。

Each string array will have the same number of elements. 每个字符串数组将具有相同数量的元素。

If i have a random given string "rat" for example, i would like to return the number 3, which is the mapping integer from the corresponding string array. 例如,如果我有一个随机的给定字符串“ rat”,我想返回数字3,它是来自相应字符串数组的映射整数。

Something like a dictionary or a list. 诸如字典或列表之类的东西。 Any thoughts would be appreciated. 任何想法将不胜感激。

What you need is a Map in java. 您需要的是Java中的Map。

Sample Usage of Map : 地图的用法示例:

 Map<String,String> data = new HashMap<String,String>();
`   for(int i=0;i<words.length;i++) {
    data.put(words[i],numbers[i]);
 }

For more details please refer to https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html 有关更多详细信息,请参阅https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html

Oracle Docs for HashMap 适用于HashMap的Oracle文档

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        String[] words = {"cat","dog", "rat", "pet", "bat"};
        String[] numbers = {"1","2", "3", "4", "5"};

        Map<String,String> keyval = new HashMap<String,String>();

        for(int  i = 0 ; i < words.length ; i++ ){
            keyval.put(words[i], numbers[i]);
        }

        String searchKey = "rat";

        if(keyval.containsKey(searchKey)){
            System.out.println(keyval.get(searchKey));
        }
    }

}

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

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