user2934930 user2934930 - 1 year ago 72
Java Question

Make separate list of same object in the list

I have list of object and there is a chance that we have multiple duplicates of different object now my goals is to iterate through the list and store same object in separate list. Any ideas on how to achieve that.

Input list


What i want to achieve




Answer Source

You could probably do this with the new stream API. But I'm not very familiar with it yet. If I were you, I would do this:

int[] list = {1, 3, 3, 1, 4};
HashMap<Integer, ArrayList<Integer>> listsMap = new HashMap<>();
for (int i: list) {
    if (!listsMap.containsKey(i)) {
        listsMap.put(i, new ArrayList<>());
    } else {


First, we create a map that stores the lists (line 2). This is used to find the correct list to add the item into when we loop through the array.

Now we loop through the array (line 3). We check whether we have already encountered the item before (line 4). If we have not, add a new ArrayList to the map with the current item as the key (line 5). Then we put the item into the newly created array(line 6). If we have encountered the item before, just add the item to the array with the key of that item(line 8).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download