2

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.

0

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.