使用 Stream 将 List 转换为 Hashmap
convrt List to Hash Map with Stream
我有这个列表:List<String> g= Arrays.asList("aa","ab","aaa","aaaa");
如何使用 java 流打印输出 :
{2=[2]} //two-letter word = 2
{3=[1]} //three-letter word = 1
{4=[1]} //four-letter word = 1
我这样写:
g.stream().collect(Collectors.groupingBy(String::length)).forEach((k,v) -> System.out.println(String.format(k,v)));
但在输出上打印:
{2=[aa, ab]}
{3=[aaa]}
{4=[aaaa]}
这是你想要的吗?
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);
输出:
{0=[aa]}
{1=[ab]}
{2=[aaa]}
{3=[aaaa]}
试试这个:
g.stream().forEach(elt ->{
System.out.println("{"+ g.indexOf(elt)+"=["+elt+"]}");
});
List<String> g= Arrays.asList("aa","ab","aaa","aaaa");
g.stream()
.collect(Collectors.groupingBy(String::length))
.forEach((k,v) -> System.out.printf("{%d=[%d]}%n",k ,v.size()));
输出:
{2=[2]}
{3=[1]}
{4=[1]}
我有这个列表:List<String> g= Arrays.asList("aa","ab","aaa","aaaa");
如何使用 java 流打印输出 :
{2=[2]} //two-letter word = 2
{3=[1]} //three-letter word = 1
{4=[1]} //four-letter word = 1
我这样写:
g.stream().collect(Collectors.groupingBy(String::length)).forEach((k,v) -> System.out.println(String.format(k,v)));
但在输出上打印:
{2=[aa, ab]}
{3=[aaa]}
{4=[aaaa]}
这是你想要的吗?
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);
输出:
{0=[aa]}
{1=[ab]}
{2=[aaa]}
{3=[aaaa]}
试试这个:
g.stream().forEach(elt ->{
System.out.println("{"+ g.indexOf(elt)+"=["+elt+"]}");
});
List<String> g= Arrays.asList("aa","ab","aaa","aaaa");
g.stream()
.collect(Collectors.groupingBy(String::length))
.forEach((k,v) -> System.out.printf("{%d=[%d]}%n",k ,v.size()));
输出:
{2=[2]}
{3=[1]}
{4=[1]}