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.

kokodee
  • 285
  • 1
  • 3
  • 15
  • 1
    Possible duplicate of [How to map two arrays to one HashMap in Java?](http://stackoverflow.com/questions/30339679/how-to-map-two-arrays-to-one-hashmap-in-java) – AMACB Mar 03 '16 at 04:36

2 Answers2

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

Sumit Rathi
  • 693
  • 8
  • 15
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));
        }
    }

}
faizal vasaya
  • 517
  • 3
  • 12