*/
package org.sonar.core.util.stream;
+import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
merger,
ImmutableListMultimap.Builder::build);
}
+
+ /**
+ * Applies the specified {@link Joiner} to the current stream.
+ *
+ * @throws NullPointerException of {@code joiner} is {@code null}
+ * @throws IllegalStateException if a merge operation happens because parallel processing has been enabled on the current stream
+ */
+ public static <E> Collector<E, List<E>, String> join(Joiner joiner) {
+ requireNonNull(joiner, "Joiner can't be null");
+
+ return Collector.of(
+ ArrayList::new,
+ List::add,
+ mergeNotSupportedMerger(),
+ joiner::join);
+ }
+
+ private static <R> BinaryOperator<R> mergeNotSupportedMerger() {
+ return (m1, m2) -> {
+ throw new IllegalStateException("Parallel processing is not supported");
+ };
+ }
}
*/
package org.sonar.core.util.stream;
+import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.guava.api.Assertions.assertThat;
import static org.sonar.core.util.stream.Collectors.index;
+import static org.sonar.core.util.stream.Collectors.join;
import static org.sonar.core.util.stream.Collectors.toArrayList;
import static org.sonar.core.util.stream.Collectors.toHashSet;
import static org.sonar.core.util.stream.Collectors.toList;
assertThat(multimap).contains(entry(1, "A"), entry(2, "B"), entry(3, "C"));
}
+ @Test
+ public void join_on_empty_stream_returns_empty_string() {
+ assertThat(Collections.emptyList().stream().collect(join(Joiner.on(",")))).isEmpty();
+ }
+
+ @Test
+ public void join_fails_with_NPE_if_joiner_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Joiner can't be null");
+
+ join(null);
+ }
+
+ @Test
+ public void join_applies_joiner_to_stream() {
+ assertThat(Arrays.asList("1", "2", "3", "4").stream().collect(join(Joiner.on(","))))
+ .isEqualTo("1,2,3,4");
+ }
+
+ @Test
+ public void join_supports_null_if_joiner_does() {
+ Stream<String> stream = Arrays.asList("1", null).stream();
+
+ expectedException.expect(NullPointerException.class);
+
+ stream.collect(join(Joiner.on(",")));
+ }
+
private void expectedDuplicateKey1IAE() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Duplicate key 1");