How to reference the result of reduce() operation in Java 8?

  • A+

I was trying to write a mkString function in Java8, a la Scala's useful mkString and ran into 2 issues that I could use some help on:

  1. I am unable to make the first argument of mkString a generic Collection reference like Collection<Object> c and have invokers call with ANY type of collection.

  2. Unable to reference the returned result of reduce() in-line to access the result's length to remove the extra leading separator.

Here's the code :

public static void main(String[] args) {     List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);     System.out.println(mkString(numbers, ","));  }  public static String mkString(Collection<Integer> c, String sep) {     return             .map(e -> String.valueOf(e))             .reduce("", (a, b) -> a + sep + b)             .substring(1, <<>>.length); } 


You can do it like :

public static <T>  String mkString(Collection<T> c, String sep) { // generic impl     return             .map(String::valueOf)             .reduce("", (a, b) -> a + sep + b)             .substring(1); // substring implementation to strip leading character } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: