Solved

Map vs. Set

Posted on 2013-01-24
4
294 Views
Last Modified: 2013-02-02
Hi there;

Can the same keys occur in maps in Java?
Also for same key but different value mapping, what can be used?

A 1 4
A 23 5
A 345 4
-------
B 12 6
B 23 7
B 34444 8

12 23 345 in A and 12 23 34444 in B are unique keys for each group, so how can i group those, so that I can reach let's say longest element? Any stragies? Where to put where? Which collections?

Regards.
0
Comment
Question by:jazzIIIlove
4 Comments
 
LVL 4

Expert Comment

by:tvedtem
ID: 38816860
A Map maps keys to values.
A single key can only have one value.
There is nothing to stop you making the value a List object, should you need a 1-many data structure..

Does that answer your question ?  I didn't understand what you meant by reaching the 'longest element'.  A HashMap will allow you to find entries by key.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 38817116
The below is some code that may be able to help what you want. It is based on MANY assumptions, as the description that you give above (and in your previous, now delete, question) is way too vague. But hopefully, it may be a starting point. If you can say where the below is not in line with your requirements, I can help you further.
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TestMapOfLists {
    
    public static void main(String[] args) {
        Map<String, List<ItemDetail>> map = new HashMap<String, List<ItemDetail>>();
        map.put("A", Arrays.asList(new ItemDetail("1", 4), new ItemDetail("23", 5), new ItemDetail("345", 4)));
        map.put("B", Arrays.asList(new ItemDetail("12", 6), new ItemDetail("23", 7), new ItemDetail("34444", 8)));
        
        System.out.println("Map data\n--------\n" + map);
        
        
        Map<String, ItemDetail> results = new HashMap<String, TestMapOfLists.ItemDetail>();
        
        for (Map.Entry<String, List<ItemDetail>> entry : map.entrySet()) {
            int maxLength = 0;
            
            for (ItemDetail itemDetail : entry.getValue()) {
                int length = itemDetail.getId().length();
                
                if (length > maxLength) {
                    results.put(entry.getKey(), itemDetail);
                    maxLength = length;
                }
            }
        }
        
        System.out.println("Results\n--------\n" + results);
    }
    
    private static class ItemDetail {
        private String id;
        private int price;
        
        public ItemDetail(String id, int price) {
            this.id = id;
            this.price = price;
        }

        public String getId() {
            return id;
        }

        public int getPrice() {
            return price;
        }

        @Override
        public String toString() {
            return id + ": " + price;
        }
    }
}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38818265
Can the same keys occur in maps in Java?
No
Also for same key but different value mapping, what can be used?
You need a 'multimap'
http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/MultiMap.html
You can of course make your own multimap without 3rd party libraries if you want
0
 
LVL 26

Accepted Solution

by:
dpearson earned 500 total points
ID: 38821521
The basic way to support this is to build a structure like this:

Map<String, List<String>> multiKeyMap = new HashMap<String, List<String>>() ;

to add a value you do this:
if (multiKeyMap.get(key) == null) multiKeyMap.put(key, new ArrayList<String>()) ;
multiKeyMap.get(key).add(value) ;

to get the list of values for a key you do this:
multiKeyMap.get(key) ; // Returns a list

You should be able to put the rest together pretty easily once you start from this.

Doug
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now