0

for example

 Map<String, List<String>> headers = connection.getHeaderFields();

    for (String key: headers.keySet()){
        for (String value: headers.get(key)){
            System.out.println(key+":"+value);
        }
    }

Can this code change to the (Method References) somehow like this?

Consumer<String> consumer = headers::get;
headers.keySet().forEach(consumer);

But this is not correct.I think there is a way to do this:

  1. Consumer<String> consumer = headers::get;
  2. BiConsumer<String, String> header = (key, value) -> System.out.println(key+":"+value);
  3. combine 1,2

Is my though right?

lxacoder
  • 191
  • 1
  • 11

3 Answers3

2

Looks like a case where you can utilize the flatMap:

headers.entrySet().stream()
  .flatMap(k -> k.getValue().stream().map(v -> k + ":" + v))
  .forEach(System.out::println);

Regarding your question about Consumer and BiConsumer, it's totally missed - those are just Functional Interfaces and can be used only for representing functions - they need to be passed somewhere to be used.

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
0

First, change these for loops into a loop on map entries to improve efficiency (Q&A on iterating maps in Java):

for (Map.Entry<String, List<String>> entry : headers.entrySet()){
    for (String value: entry.getValue()){
        System.out.println(entry.getKey()+":"+value);
    }
}

Now you are ready to convert it to stream-based iteration:

headers.entrySet().forEach(entry -> {
    entry.getValue().forEach(value -> System.out.println(entry.getKey()+":"+value))
});
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You can use something like this

headers.forEach((key, value) -> {
        value.forEach((current) -> {
            System.out.println(key + ":" + current);
        });
    });
amitdonanand
  • 101
  • 3
  • 16