Merchuk Hul
Merchuk Hul

Reputation: 275

How to create a view of all elements in many collections in Java?

I have this boilderplace code

for(Person p: school.getStudents())
    p.setName(null);

for(Person p: school.getTeachers())
    p.setName(null);

for(Person p: school.getStrangers())
    p.setName(null);

I it possible to "combine" all those collections in a view (ie. avoid copying / allocating memory like via addAll()) and iterate over the view?

e.g.

for(Person p: allOf(school.getStudents(), school.getTeachers(), school.getStrangers())
    p.setName(null);

Upvotes: 0

Views: 62

Answers (2)

Phash
Phash

Reputation: 428

You could create a method, which does this for you.

something like:

private List<Person> allOf(List<Person>... collections) {
    List<Person> result = new ArrayList<Person>();
    for (List<Person> element : collections) {
        result.addAll(element);
    }
    return result;
}

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213351

You can use Guava's Iterables.concat() method. It creates a view over multiple iterables passed to it, and then you can iterate over the resulting Iterable.

Upvotes: 3

Related Questions