N
N
neverbethesameagain2020-05-29 19:42:04
Java
neverbethesameagain, 2020-05-29 19:42:04

How to display keys in Java Map in a different way?

Have a collection

Map<String, String> map = new HashMap<>();
        map.put("Sim", "Sim");
        map.put("Tom", "Tom");
        
        for(String keys: map.keySet()){
            System.out.println(keys);
        }

We derive the keys in the way that can be seen above. But there is a way for key and value in the form:

map.forEach((k, v) -> System.out.println("Key: " + k + " Value: " + v));


Is it possible to output only k(key) or v(value) with it?? For if you try like this:
map.forEach((k) -> System.out.println(k));
then an error takes off
error: incompatible types: incompatible parameter types in lambda expression
        map.forEach((k) -> System.out.println(k));
                    ^

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-05-29
@neverbethesameagain

This is what happens when you don't understand the meaning of the code you copy.
(k, v) -> ...
it's a lambda, a syntactic sugar for implementing functional interfaces (interfaces that have one abstract method).
Map::foreach just accepts such an interface

BiConsumer<? super K,? super V>
с
методом
void	accept(T t, U u)

Thus, the names k, v are just lambda parameters, they can be anything. And the lambda, as an implementation of the accept method of the BiConsumer interface, must take two arguments.
You don't have to use them if you don't need them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question