Java map два значения

HashMap with multiple values under the same key

Is it possible to implement a HashMap with one key and two values?
Just as HashMap? If not, is there any other way to implement the storage of multiple values e.g. one key and two values?

21 Answers 21

  1. Use a map that has a list as the value. Map> .
  2. Create a new wrapper class and place instances of this wrapper in the map. Map .
  3. Use a tuple like class (saves creating lots of wrappers). Map> .
  4. Use mulitple maps side-by-side.

Examples

1. Map with list as the value

// create our map Map> peopleByForename = new HashMap<>(); // populate it List people = new ArrayList<>(); people.add(new Person("Bob Smith")); people.add(new Person("Bob Jones")); peopleByForename.put("Bob", people); // read from it List bobs = peopleByForename["Bob"]; Person bob1 = bobs[0]; Person bob2 = bobs[1]; 

The disadvantage with this approach is that the list is not bound to exactly two values.

2. Using wrapper class

// define our wrapper class Wrapper < public Wrapper(Person person1, Person person2) < this.person1 = person1; this.person2 = person2; >public Person getPerson1() < return this.person1; >public Person getPerson2() < return this.person2; >private Person person1; private Person person2; > // create our map Map peopleByForename = new HashMap<>(); // populate it peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"), new Person("Bob Jones")); // read from it Wrapper bobs = peopleByForename.get("Bob"); Person bob1 = bobs.getPerson1(); Person bob2 = bobs.getPerson2(); 

The disadvantage to this approach is that you have to write a lot of boiler-plate code for all of these very simple container classes.

Читайте также:  Welcome to the jungle

3. Using a tuple

// you'll have to write or download a Tuple class in Java, (.NET ships with one) // create our map Map peopleByForename = new HashMap<>(); // populate it peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith", new Person("Bob Jones")); // read from it Tuple bobs = peopleByForename["Bob"]; Person bob1 = bobs.Item1; Person bob2 = bobs.Item2; 

This is the best solution in my opinion.

4. Multiple maps

// create our maps Map firstPersonByForename = new HashMap<>(); Map secondPersonByForename = new HashMap<>(); // populate them firstPersonByForename.put("Bob", new Person("Bob Smith")); secondPersonByForename.put("Bob", new Person("Bob Jones")); // read from them Person bob1 = firstPersonByForename["Bob"]; Person bob2 = secondPersonByForename["Bob"]; 

The disadvantage of this solution is that it’s not obvious that the two maps are related, a programmatic error could see the two maps get out of sync.

Источник

adding multiple entries to a HashMap at once in one statement

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:

 hashMap.put("One", new Integer(1)); // adding value into HashMap hashMap.put("Two", new Integer(2)); hashMap.put("Three", new Integer(3)); 
[NSDictionary dictionaryWithObjectsAndKeys: @"w",[NSNumber numberWithInt:1], @"K",[NSNumber numberWithInt:2], @"e",[NSNumber numberWithInt:4], @"z",[NSNumber numberWithInt:5], @"l",[NSNumber numberWithInt:6], nil] 

11 Answers 11

You can use the Double Brace Initialization as shown below:

As a piece of warning, please refer to the thread Efficiency of Java “Double Brace Initialization» for the performance implications that it might have.

@user387184 Yeah, they call it «double brace initializer». See this topic: stackoverflow.com/questions/924285/…

You should not use this method. It creates a new class for every time that you use it, which has much worse performance than just plainly creating a map. See stackoverflow.com/questions/924285/…

The reason I downvoted this is because it didn’t explain that this creates a new class for every time that you use it. I think that people should be aware of the tradeoffs of doing it this way.

@TimoTürschmann Seems that if I ever needed static initialization of a map like this, that it would also be static, eliminating the every time you use it performance penalty — you’d have that penalty once. I can’t see any other time that one would want this kind of initialization without the variable being static (e.g., would anyone ever use this in a loop?). I may be wrong though, programmers are inventive.

Since Java 9, it is possible to use Map.of(. ) , like so:

Map immutableMap = Map.of("One", 1, "Two", 2, "Three", 3); 

This map is immutable. If you want the map to be mutable, you have to add:

Map hashMap = new HashMap<>(immutableMap); 

If you can’t use Java 9, you’re stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.

After adding 10 entries, it throws strange error «can not resolve method», is this bug with this method ?

@vikramvi yes If you look at the documentation Map.of is only done up to 10 entries since it is quite laborious

You can use Google Guava’s ImmutableMap. This works as long as you don’t care about modifying the Map later (you can’t call .put() on the map after constructing it using this method):

import com.google.common.collect.ImmutableMap; // For up to five entries, use .of() Map littleMap = ImmutableMap.of( "One", Integer.valueOf(1), "Two", Integer.valueOf(2), "Three", Integer.valueOf(3) ); // For more than five entries, use .builder() Map bigMap = ImmutableMap.builder() .put("One", Integer.valueOf(1)) .put("Two", Integer.valueOf(2)) .put("Three", Integer.valueOf(3)) .put("Four", Integer.valueOf(4)) .put("Five", Integer.valueOf(5)) .put("Six", Integer.valueOf(6)) .build(); 

Maps have also had factory methods added in Java 9. For up to 10 entries Maps have overloaded constructors that take pairs of keys and values. For example we could build a map of various cities and their populations (according to google in October 2016) as follow:

Map cities = Map.of("Brussels", 1_139000, "Cardiff", 341_000); 

The var-args case for Map is a little bit harder, you need to have both keys and values, but in Java, methods can’t have two var-args parameters. So the general case is handled by taking a var-args method of Map.Entry objects and adding a static entry() method that constructs them. For example:

Map cities = Map.ofEntries( entry("Brussels", 1139000), entry("Cardiff", 341000) ); 

Java has no map literal, so there’s no nice way to do exactly what you’re asking.

If you need that type of syntax, consider some Groovy, which is Java-compatible and lets you do:

def map = [name:"Gromit", likes:"cheese", id:1234] 

Here’s a simple class that will accomplish what you want

import java.util.HashMap; public class QuickHash extends HashMap  < public QuickHash(String. KeyValuePairs) < super(KeyValuePairs.length/2); for(int i=0; i> 
Map Foo=new QuickHash( "a", "1", "b", "2" ); 
 boolean x; for (x = false, map.put("One", new Integer(1)), map.put("Two", new Integer(2)), map.put("Three", new Integer(3)); x;); 

Ignoring the declaration of x (which is necessary to avoid an «unreachable statement» diagnostic), technically it’s only one statement.

Omg i have searched for this today,how this code works? I have added it into the code for testing but i can’t figure it out how it works internally. 🙂

You could add this utility function to a utility class:

public static Map mapOf(Object. keyValues) < Mapmap = new HashMap<>(keyValues.length / 2); for (int index = 0; index < keyValues.length / 2; index++) < map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]); >return map; > Map map1 = YourClass.mapOf(1, "value1", 2, "value2"); Map map2 = YourClass.mapOf("key1", "value1", "key2", "value2"); 

Note: in Java 9 you can use Map.of

This method shouldn’t be used since the implementation is not type safe! Example: Map map1 = mapOf(1, «value1», «key», 2, 2L);

Based on solution, presented by @Dakusan (the class defining to extend the HashMap), I did it this way:

 public static HashMap SetHash(String. pairs) < HashMaprtn = new HashMap(pairs.length/2); for ( int n=0; n
HashMap hm = SetHash( "one","aa", "two","bb", "tree","cc"); 

(Not sure if there is any disadvantages in that way (I am not a java developer, just has to do some task in java), but it works and seems to me comfortable.)

We can use JSON to achieve this, like following using Gson

Map hashMap = new Gson().fromJson("",HashMap.class); 
Map hashMap = new ObjectMapper().readValue("",HashMap.class); 

Another approach may be writing special function to extract all elements values from one string by regular-expression:

import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example < public static void main (String[] args)< HashMaphashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3' "); System.out.println(hashMapStringInteger); // > private static HashMap createHashMapStringIntegerInOneStat(String str) < HashMapreturnVar = new HashMap(); String currentStr = str; Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$"); // Parse all elements in the given string. boolean thereIsMore = true; while (thereIsMore) < Matcher matcher = pattern1.matcher(currentStr); if (matcher.find()) < returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2))); currentStr = matcher.group(3); >else < thereIsMore = false; >> // Validate that all elements in the given string were parsed properly if (currentStr.length() > 0) < System.out.println("WARNING: Problematic string format. given String: " + str); >return returnVar; > > 

Источник

Hashmap holding different data types as values for instance Integer, String and Object

Then how to store the values of different data type with a single key into the hashmap?

There are two ways this question can be read: (1) How to have each HashMap element represent a collection of data and (2) how create a HashMap wherein the elements are of nonuniform type. I believe that the intended meaning is #1, but I am grateful for the answers to #2.

5 Answers 5

If you don't have Your own Data Class, then you can design your map as follows

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapTest < public static void main(String[] args) < Mapmap=new HashMap(); Demo d1= new Demo(1,"hi",new Date(),1,1); Demo d2= new Demo(2,"this",new Date(),2,1); Demo d3= new Demo(3,"is",new Date(),3,1); Demo d4= new Demo(4,"mytest",new Date(),4,1); //adding values to map map.put(d1.getKey(), d1); map.put(d2.getKey(), d2); map.put(d3.getKey(), d3); map.put(d4.getKey(), d4); //retrieving values from map Set keySet= map.keySet(); for(int i:keySet) < System.out.println(map.get(i)); >//searching key on map System.out.println(map.containsKey(d1.getKey())); //searching value on map System.out.println(map.containsValue(d1)); > > class Demo < private int key; private String message; private Date time; private int count; private int version; public Demo(int key,String message, Date time, int count, int version)< this.key=key; this.message = message; this.time = time; this.count = count; this.version = version; >public String getMessage() < return message; >public Date getTime() < return time; >public int getCount() < return count; >public int getVersion() < return version; >public int getKey() < return key; >@Override public String toString() < return "Demo [message=" + message + ", time=" + time + ", count=" + count + ", version=" + version + "]"; >> 

Источник

HashMap: One Key, multiple Values

I can get the first value for a key by using the member function of HashMap::get though the third one? I cannot find any code unfortunately.

Sounds like you might be a little confused about the difference between keys and hashed keys. Hopefully this will set you straight: en.wikipedia.org/wiki/Hashmap

15 Answers 15

Libraries exist to do this, but the simplest plain Java way is to create a Map of List like this:

Map> multiMap = new HashMap<>(); 

this solution would only work if the objects in the ArrayList are from the same type. S, f.e. it's not possible to have a key with a int and a double value..

@gaurav: It's been so long since I've been in the Java world that I wouldn't like to say. I'd look at Guava though.

It sounds like you're looking for a multimap. Guava has various Multimap implementations, usually created via the Multimaps class.

I would suggest that using that implementation is likely to be simpler than rolling your own, working out what the API should look like, carefully checking for an existing list when adding a value etc. If your situation has a particular aversion to third party libraries it may be worth doing that, but otherwise Guava is a fabulous library which will probably help you with other code too 🙂

Map> multiMap = new HashMap>(); 

where the Pair is a parametric class

public class Pair  < A first = null; B second = null; Pair(A first, B second) < this.first = first; this.second = second; >public A getFirst() < return first; >public void setFirst(A first) < this.first = first; >public B getSecond() < return second; >public void setSecond(B second) < this.second = second; >> 

This is what i found in a similar question's answer

Map> hm = new HashMap>(); List values = new ArrayList(); values.add("Value 1"); values.add("Value 2"); hm.put("Key1", values); // to get the arraylist System.out.println(hm.get("Key1")); 

A standard Java HashMap cannot store multiple values per key, any new entry you add will overwrite the previous one.

Have you got something like this?

If so, you can iterate through your ArrayList and get the item you like with arrayList.get(i).

I found the blog on random search, i think this will help for doing this: http://tomjefferys.blogspot.com.tr/2011/09/multimaps-google-guava.html

public class MutliMapTest < public static void main(String. args) < MultimapmyMultimap = ArrayListMultimap.create(); // Adding some key/value myMultimap.put("Fruits", "Bannana"); myMultimap.put("Fruits", "Apple"); myMultimap.put("Fruits", "Pear"); myMultimap.put("Vegetables", "Carrot"); // Getting the size int size = myMultimap.size(); System.out.println(size); // 4 // Getting values Collection fruits = myMultimap.get("Fruits"); System.out.println(fruits); // [Bannana, Apple, Pear] Collection vegetables = myMultimap.get("Vegetables"); System.out.println(vegetables); // [Carrot] // Iterating over entire Mutlimap for(String value : myMultimap.values()) < System.out.println(value); >// Removing a single value myMultimap.remove("Fruits","Pear"); System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear] // Remove all values for a key myMultimap.removeAll("Fruits"); System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!) > > 

Источник

Оцените статью