'Analysis the hashmap keys as 3 keys in each one lane

I'm trying to analyze a hashmap keys, so I want to make every 3 keys from the hashmap send as one line, and then after sending 3 keys it will put a "\n" so it will go to the next line and put another 3 values and etc... till the hashmap keys print all.

Example:

key1 / key2 / key3
key4 / key5 / key6
key7 / key8

My code for now is :


    Map<String, Integer> map = new HashMap<>();
    map.put("key1", 0); 
    map.put("key2", 1); 
    map.put("key3", 2); 
    map.put("key4", 3); 
    map.put("key5", 4); 
    map.put("key6", 5); 
    map.put("key7", 6); 
    map.put("key8", 7); 
    
    System.out.println(map.keySet().stream().collect(Collectors.joining(" / ")));

and the result is only in one line.



Solution 1:[1]

I finally find out that the easiest way to do it which is, it's only in one line :


AtomicInteger counter = new AtomicInteger(0);
 
System.out.println(map.keySet().stream().map(map -> ((counter.getAndAdd(1) % 3 == 0) ? "\n" : " / ") + map).collect(Collectors.joining("")));

Note: make sure that I used here the AtomicInteger and get the counter as counter.getAndAdd() not counter.addAndGet() which put me in 30 minutes thinking about why it's not working.

thanks to @shmosel because he is the one who gives the code and I just change a few things that make it in one line only.

the result is this:

key1 / key2 / key3
key4 / key5 / key6
key7 / key8 / key9
key10 / key11

Solution 2:[2]

The solution I propose is the following:

The idea is to keep a counter to know when it is multiples of three and jump to a new line.

public static void main(String[] args) {
        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("key1", 0);
        map.put("key2", 1);
        map.put("key3", 2);
        map.put("key4", 3);
        map.put("key5", 4);
        map.put("key6", 5);
        map.put("key7", 6);
        map.put("key8", 7);
        map.put("key9", 8);
        map.put("key10", 9);


        int counter = 1;

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String key = entry.getKey();
            if((counter)%3==0)
            {
                System.out.println(key);
            }
            else{
                System.out.print(key+" / ");
            }
            counter++;
        }

The output is the following:

enter image description here

Remark: I changed from HashMap<>() to LinkedHashMap<>() because HashMap does not maintain an insertion order and LinkedHashMap does.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gerardo Gonzalez - Nemis