1

Unfortuantely, I'm in Java 7 so I can't use any Java 8's facilities.

I have the following enum:

public enum Type { MAILING, RESEPT, CURRENT, //... USER } 

and the class container of that type:

public class Container { public Type getType() { // Impl } } 

Now I have some List<Container>. How can I split it into List<List<Container>> such that any List<Container> in the List<List<Container>> contains only Containers with the same getType().

3 Answers 3

3

If you have Java 8, you can use the Stream-API's Collectors.groupingBy(...). Then you get a Map<Type, List<Container>> returned. Then you can just loop over the values of the map and put it into a list.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry for not specifying that important information. I'm still in Java 7
Is there some Java <8 way to solve it? Probably with Common or guava.
2

Here's a slightly different Java 7 approach:

List<Container> containers = new ArrayList<>(); containers.add(/* ... */); containers.add(/* ... */); containers.add(/* ... */); containers.add(/* ... */); containers.add(/* ... */); containers.add(/* ... */); Map<Type, List<Container>> split = new HashMap<>(); for (Container container : containers) { if (!split.containsKey(container.getType())) { split.put(container.getType(), new ArrayList<Container>()); } split.get(container.getType()).add(container); } List<List<Container>> listOfLists = new ArrayList<>(split.values()); 

3 Comments

One note, Map doesn't contain the contains method. You probably meant containsKey() instead.
Thanks, Updated. I didn't actually test this :-)
@St.Antario Just a note - if you are using Guava (maybe, judging by your comment on the other answer), you can use a MultiMap, that gets rid of some boilerplate code.
2

In case of Java 7, I would recommend looping through the enums values().

List<Container> completeList = new ArrayList<>(); List<List<Container>> splitList = new ArrayList<>(); for (Type type : Type.values()) { List<Container> containerTypeList = new ArrayList<>(); for (Container c : completeList) { if (c.getType().equals(type)) { containerTypeList.add(c); } } splitList.add(containerTypeList); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.