Try to search your question here, if you can't find : Ask Any Question Now ?

Java Stream collect method

HomeCategory: stackoverflowJava Stream collect method
Avatargaurav asked 5 months ago

When using String::new as the Supplier of collect method, i saw the output is not collected and return nothing at the end.

If using StringBuilder, then works fine.

Why String::new can’t do collect?

List<String> list2 = Arrays.asList("a", "b", "c", "d", "e", "f", "g");

String collect = list2.stream().collect(String::new, (res, elem) -> {
    res = res.concat(elem);
    System.out.printf("res=%s, elem=%sn", res, elem);
}, (res1, res2) -> {
    System.out.printf("res1=%s, res2=%sn", res1, res2);
});
System.out.println("collect=" + collect);

Output:

res=a, elem=a  
res=b, elem=b  
res=c, elem=c  
res=d, elem=d  
res=e, elem=e  
res=f, elem=f  
res=g, elem=g  
collect=
1 Answers
Best Answer
AvatarMannu answered 5 months ago
Your Answer

4 + 19 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com