Rahul
Rahul

Reputation: 331

How to iterate through a 2D LinkedHashSet and print its contents?

I am using a 2D LinkedHashSet for my program. I was wondering how I can iterate through the two dimensional HashSet and print its contents without doing this:

System.out.println(name of initialized HashSet)

Here is my code for initialization of the 2D LinkedHashSet:

LinkedHashSet<LinkedHashSet<String>> block = new LinkedHashSet<LinkedHashSet<String>>();

Upvotes: 0

Views: 464

Answers (2)

Matt Berteaux
Matt Berteaux

Reputation: 763

You can use 2 loops for this, similar to how you would for an array:

for (Set<String> innerSet : block) {
    for (String string : innerSet) {
        System.out.println(string);
    }
}

You can also use streams to print each element:

block.stream()
        .flatMap(Collection::stream)
        .forEach(System.out::println);

Upvotes: 4

Turing85
Turing85

Reputation: 20185

If one wants to use a functional solution, one could use the following:

Ideone demo

import java.util.LinkedHashSet;

public class Streamify {
    public static void main (final String... args) {
        final LinkedHashSet<LinkedHashSet<String>> block = new LinkedHashSet<>();
        final LinkedHashSet<String> lineOne = new LinkedHashSet<>();
        lineOne.add("Hello");
        lineOne.add("World");
        block.add(lineOne);
        final LinkedHashSet<String> lineTwo = new LinkedHashSet<>();
        lineTwo.add("Hi");
        lineTwo.add("Universe");
        block.add(lineTwo);

        block.forEach(line -> {
            line.forEach(System.out::print);
            System.out.println();
        });
    }
}

Upvotes: 2

Related Questions