Skip to content

Instantly share code, notes, and snippets.

@skht777
Last active December 29, 2016 12:53
Show Gist options
  • Select an option

  • Save skht777/fcc8a890cfbd7c8bca386b176f9cc508 to your computer and use it in GitHub Desktop.

Select an option

Save skht777/fcc8a890cfbd7c8bca386b176f9cc508 to your computer and use it in GitHub Desktop.
ZipWithのような何か
package test;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* @author skht777
*/
public class StrZipWith {
public static <T, S, U> List<U> zipWith(BiFunction<T, S, U> reduce, List<T> f, List<S> s) {
return zipWith(reduce, f, s, IntStream.of(f.size(), s.size()).min().getAsInt() - 1).collect(Collectors.toList());
}
public static String StrZipWith(BiFunction<String, String, String> reduce, String f, String s) {
return zipWith(reduce, strToList(f), strToList(s)).stream().collect(Collectors.joining());
}
private static <T, S, U> Stream<U> zipWith(BiFunction<T, S, U> reduce, List<T> f, List<S> s, int idx) {
return idx < 0 ? Stream.empty() : Stream.concat(zipWith(reduce, f, s, idx - 1), Stream.of(reduce.apply(f.get(idx), s.get(idx))));
}
private static List<String> strToList(String s) {
return IntStream.range(0, s.length()).mapToObj(i -> String.valueOf(s.charAt(i))).collect(Collectors.toList());
}
public static void main(String[] args) {
final String pt = "パトカー";
final String tx = "タクシー";
System.out.println(StrZipWith(((p, t) -> p + t), pt, tx));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment