javalinkedhashset

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>>();

Solution

  • 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);