0

I have two methods to iterate through a hash map containing a key(String) and a value(Arraylist) and add all the values from the Arraylists to a single Arraylist.

Method one did not work so I created Method two which fixed the issue but i'm not sure why method one did not work. Could someone please explain why method two works and method one does not?

Method 1

public ArrayList<Person> getPeopleList() 
{
    Iterator<ArrayList<Person>> iter = people.values().iterator();

    ArrayList<Person> allPersons = new ArrayList<>();
    while (iter.hasNext()) 
    {
        for (int i = 0; i < iter.next().size(); i++) 
        {
            allPersons.add(iter.next().get(i));
        }

    }
    return allPersons;
}

Method 2

public ArrayList<Person> getPeopleList() 
{
    Iterator<ArrayList<Person>> iter = people.values().iterator();

    ArrayList<Person> allPersons = new ArrayList<>();

    ArrayList<Person> persons;
    while (iter.hasNext()) 
    {
        persons = iter.next();
        for (Person p : persons) 
        {
            allPersons.add(p);
        }

    }
    return allPersons;
}
6
  • should be posted on codereview.stackexchange.com Commented Apr 18, 2017 at 16:04
  • 2
    @AmitK Not quite, OP is asking about problem, not potential improvements for already working code. Commented Apr 18, 2017 at 16:05
  • 1
    Method 1 is massively broken, as it's going to be calling next() twice per inner iteration, when it shouldn't be calling iter.next() at all - you want a single call to iter.next() per outer iteration. Commented Apr 18, 2017 at 16:06
  • 1
    @AmitK "Trouble-shooting, debugging, or understanding code snippets ... is off-topic for this site." Commented Apr 18, 2017 at 16:06
  • 1
    @Babyburger: Where is the OP iterating over allPersons? Commented Apr 18, 2017 at 16:07

1 Answer 1

5
for (int i = 0; i < iter.next().size(); i++) 

This calls next() at each iteration of your for loop. You need to call it once, and store the result in a variable. Note that List has an addAll() method, making this for loop useless.

With streams, your whole code can be reduced to

return map.values().stream().flatMap(List::stream).collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

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.