gurehbgui
gurehbgui

Reputation: 14684

key value pair implementation in java?

Is there something like a KeyValuePair in Java?

I have a Very long list of elements of the following class:

public class Foo {
    int id;
    Set<String> items;
}

which is stored here:

LinkedList<Foo> myList;

each time I search for a item, I iterate over the list and search for the Item, but this takes to much time. I want to do something like this:

myList.get(123) => items of the Foo with id = 123

Upvotes: 2

Views: 25483

Answers (5)

import java.util.*;

class temp{

public static void main(String[] args){

    Map<Integer,String> map = new HashMap<Integer,String>();
    map.put(1,"anand");
    map.put(2,"bindu");
    map.put(3,"cirish");
    System.out.println(1+" = "+map.get(1));             
    System.out.println(2+" = "+map.get(2));
    System.out.println(3+" = "+map.get(3));

    Map<String,Integer> map1 = new HashMap<String,Integer>();
    map1.put("anand",1);
    map1.put("bindu",2);
    map1.put("cirish",3);
    System.out.println("anand = "+map1.get("anand"));               
    System.out.println("bindu = "+map1.get("bindu"));

    if(map1.get("cirish") != null){
        System.out.println("cirish = "+map1.get("cirish"));
    }

    if(map1.get("dinesh") != null){
        System.out.println("cirish = "+map1.get("dinesh"));
    }
}

}

Upvotes: -1

PSR
PSR

Reputation: 40338

You can use Map in Java for that purpose. It will allow key, value pairs.

Map<Integer,Set<String>> map = new HashMap<Integer,Set<String>>();

Adding item to map

Set<String> set = new HashSet<String>();
      set.add("ABC");
      set.add("DEF");
      map.put(123,set);

Getting item from map

  map .get(123)  will give  Set<String>  associated  with id  123

Upvotes: 6

Petros Tsialiamanis
Petros Tsialiamanis

Reputation: 2758

I think the MultiMap<Integer,String> is suitable in your case.

Upvotes: 1

AlexWien
AlexWien

Reputation: 28737

you would need a so called MultiMap, java dont has that by default, but you always can use a Map for that purpose.

Try using a HashMap<Integer, Set<String>>

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Try some impelementation of java.util.Map.

More info: here

Upvotes: 4

Related Questions