Home > OS >  convrt List to Hash Map with Stream
convrt List to Hash Map with Stream

Time:02-21

I have this List: List<String> g= Arrays.asList("aa","ab","aaa","aaaa");

How can I print the output using java streams:

{2=[2]}  //two-letter word = 2
{3=[1]}  //three-letter word = 1
{4=[1]}  //four-letter word = 1

I write this:

g.stream().collect(Collectors.groupingBy(String::length)).forEach((k,v) -> System.out.println(String.format("{%d=%s}",k,v)));

but print on the output:

{2=[aa, ab]}
{3=[aaa]}
{4=[aaaa]}

CodePudding user response:

Is this what you want?

List<String> g = Arrays.asList("aa", "ab", "aaa", "aaaa");

g.stream()
    .map(value -> String.format("{%s=[%s]}", g.indexOf(value), value))
    .forEach(System.out::println);

Output:

{0=[aa]}
{1=[ab]}
{2=[aaa]}
{3=[aaaa]}

CodePudding user response:

Try this:

 g.stream().forEach(elt ->{
            System.out.println("{"  g.indexOf(elt) "=[" elt "]}");
        });
  • Related