4

Есть 2 коллекции: c1 = Arrays.asList("A", "B", "C") и c2 = Arrays.asList("1", "2", "3"). Подскажите, как с помощью Stream API на Java в 1 строку сделать коллекцию {"A1", "B2", "C3"}?

1 ответ 1

4

В стандартных стримах почему-то нет операции zip, поэтому приходится прибегать к разврату типа

IntStream
  .range(0, Math.min(c1.size(), c2.size()))
  .mapToObj(i -> c1.get(i) + c2.get(i))
  .forEach(System.out::println);

Но zip есть в Guava

Streams
  .zip(c1.stream(), c2.stream(), (x, y) -> x + y)
  .forEach(System.out::println);

И в StreamEx

StreamEx.of(c1)
        .zipWith(StreamEx.of(c2), (x, y) -> x + y)
        .forEach(System.out::println);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.