0

I've been trying to group of facets by translated value, but what I always get is only one last object on the List (no dataset). Here is what I tried:

HashMap<String, List<Facet>> map = new HashMap<>();

for (Facet facet : getFacets()) {
        map.put(facet.getTranslatedValue(), new ArrayList<com.schneider.gss.model.Facet>());
        map.get(facet.getTranslatedValue()).add(facet);
    }

Can you suggest anything?

2
  • sounds like you want to use a MultiMap Commented Sep 22, 2014 at 13:31
  • 1
    MulltiMap is the way you want to go. The reason thats happening is you are replacing your ArrayList everytime you add. To fix your implementation, you need to check if there is already an ArrayList where that key is. If there is one, add the Facet to the list, if there is not, create the arraylist and add the Facet like you are currently doing Commented Sep 22, 2014 at 13:34

3 Answers 3

2

Change your for loop as below

for (Facet facet : getFacets()) {
        if(map.get(facet.getTranslatedValue()) == null) {
            map.put(facet.getTranslatedValue(), new ArrayList<com.schneider.gss.model.Facet>());
        }
        map.get(facet.getTranslatedValue()).add(facet);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You're overwriting your list each time you get an identical translated value with a new ArrayList. Instead, you should check if it exists:

HashMap<String, List<Facet>> map = new HashMap<>();

for (Facet facet : getFacets()) {
    //get the list
    ArrayList<com.schneider.gss.model.Facet> list = map.get(facet.getTranslatedValue());
    //if list doesn't exist, create it
    if(list == null) {
        map.put(facet.getTranslatedValue(), new ArrayList<com.schneider.gss.model.Facet>());
    }
    //then add to list
    map.get(facet.getTranslatedValue()).add(facet);
}

Comments

0

in Guava there is class Multimap (or ArrayListMultimap) which does exactly what you need

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.