fork download
  1. import java.util.*;
  2. import java.util.function.*;
  3. import java.util.stream.*;
  4.  
  5. class Ideone {
  6. public static void main(String args[]){
  7. List<String> strings = List.of("a", "bb", "cc", "ddd");
  8.  
  9. Map<Integer, List<Character>> result1 = strings.stream()
  10. .map(toStringList())
  11. .collect(Collectors.groupingBy(List::size
  12. , Collectors.reducing(List.of(),concat())
  13. ));
  14. System.out.println(result1);
  15.  
  16. Map<Integer,ObjStr2> result2 = strings.stream()
  17. .map(ObjStr1::new)
  18. .collect(Collectors.groupingBy(ObjStr1::getLen
  19. , Collectors.reducing(new ObjStr2(), ObjStr1::to2, ObjStr2::doReduce)));
  20.  
  21. System.out.println(result2);
  22. }
  23.  
  24. private static Function<String, List<Character>> toStringList(){
  25. return s-> s.chars()
  26. .mapToObj(c->(char) c)
  27. .collect(Collectors.toList());
  28. }
  29.  
  30. private static BinaryOperator<List<Character>> concat(){
  31. return (l1, l2) -> {
  32. return Stream.concat(l1.stream(), l2.stream()).collect(Collectors.toList());
  33. };
  34. }
  35.  
  36.  
  37. }
  38.  
  39. class ObjStr1{
  40. String str = "";
  41.  
  42. ObjStr1(String str) {
  43. this.str = str;
  44. }
  45.  
  46. static ObjStr2 to2(ObjStr1 o){
  47. return new ObjStr2(o.str);
  48. }
  49.  
  50. Integer getLen(){return str.length(); };
  51. }
  52.  
  53. class ObjStr2{
  54. String str = "";
  55.  
  56. ObjStr2(){}
  57.  
  58. ObjStr2(String str) {
  59. this.str = str;
  60. }
  61.  
  62. static ObjStr2 doReduce(ObjStr2 a, ObjStr2 b){
  63. return new ObjStr2(a.str + b.str);
  64. }
  65.  
  66. @Override
  67. public String toString(){
  68. return str;
  69. }
  70. }
Success #stdin #stdout 0.17s 37504KB
stdin
Standard input is empty
stdout
{1=[a], 2=[b, b, c, c], 3=[d, d, d]}
{1=a, 2=bbcc, 3=ddd}