Collection { public static <T> String join(List<T> list, String separator, Function<T, String> function) { String result = ""; for (int i = 0; i < list.size(); i++) { result += function.apply(list.get(i)).trim(); if (i + 1 < list.size()) { result += separator; } } return result; } private  Collection(); static String[] tail(String[] args); @SafeVarargs static T[] create(T... args); static String join(List<T> list, String separator, Function<T, String> function); static String join(List<String> list, String separator);  }
@Test public void testJoinWithFunction() { final List<FakeSpec> specs1 = Arrays.asList( new FakeSpec("a"), new FakeSpec("b"), new FakeSpec("c")); assertThat(join(specs1, ",", new Function<FakeSpec, String>() { @Override public String apply(FakeSpec fakeSpec) { return fakeSpec.getName(); } }), is("a,b,c")); final List<FakeSpec> specs2 = Arrays.asList( new FakeSpec("a"), new FakeSpec("b"), new FakeSpec("c")); assertThat(join(specs2, ", ", new Function<FakeSpec, String>() { @Override public String apply(FakeSpec fakeSpec) { return fakeSpec.getName(); } }), is("a, b, c")); final List<FakeSpec> specs3 = Arrays.asList( new FakeSpec(" a"), new FakeSpec("b "), new FakeSpec(" c ")); assertThat(join(specs3, ",", new Function<FakeSpec, String>() { @Override public String apply(FakeSpec fakeSpec) { return fakeSpec.getName(); } }), is("a,b,c")); final List<FakeSpec> specs4 = Arrays.asList( new FakeSpec(" a"), new FakeSpec("b "), new FakeSpec(" c ")); assertThat(join(specs4, ", ", new Function<FakeSpec, String>() { @Override public String apply(FakeSpec fakeSpec) { return fakeSpec.getName(); } }), is("a, b, c")); }
@Test public void testJoin() { final ArrayList<String> list = new ArrayList<>(); assertEquals("", Collection.join(list, ",")); list.add("test1"); assertEquals("test1", Collection.join(list, ",")); list.add("test2"); assertEquals("test1,test2", Collection.join(list, ",")); assertEquals("test1:sep:test2", Collection.join(list, ":sep:")); assertEquals("test1test2", Collection.join(list, "")); }
@Test public void testJoinWithFunction() { final Collection.Function<Integer, String> parityFunction = x -> x % 2 == 0 ? "even" : "odd"; final ArrayList<Integer> list = new ArrayList<>(); assertEquals("", Collection.join(list, ",", parityFunction)); list.add(1); assertEquals("odd", Collection.join(list, ",", parityFunction)); list.add(2); assertEquals("odd,even", Collection.join(list, ",", parityFunction)); assertEquals("odd:sep:even", Collection.join(list, ":sep:", parityFunction)); assertEquals("oddeven", Collection.join(list, "", parityFunction)); }