简体   繁体   中英

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 . I know in Python , it's pretty easy in two lines code. However, i'm not sure if Java provides an easier option than looping through both string arrays.

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.

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.

Something like a dictionary or a list. Any thoughts would be appreciated.

What you need is a Map in java.

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

Oracle Docs for HashMap

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));
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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