How to combine two lists without using foreach?

I initially have this code:

String[] A;
String[] B;
//...
List<String> myList= new ArrayList<>(A.length + B.length);
for (int i= 0; i< B.length; i++){
   myList.add(A[i]);
   myList.add("*".equals(B[i]) ? B[i] : doSomethingWith(B[i]));
}

How to refactor, if you use, preferably Java 8?

If, for example, I have these arrays

A = {"one", "two", "three", "four"}

B = {"five", "six", "seven", "eight"}

At the end of the code, myList will be:

myList = {"one", "five", "two", "six", "three", "seven", "four", "eight"}

+4
source share
2 answers

, , "" , , :

String[] A;
String[] B;
List<String> myList;

myList = IntStream.range(0, B.length)
                  .mapToObj(i -> new String[]
                      {
                          A[i],
                          "*".equals(B[i]) ? B[i] : doSomethingWith(B[i])
                      })
                  .flatMap(Arrays::stream)
                  .collect(Collectors.toList());

.


  • IntStream.range .

  • mapToObj , ( , IntStream::flatMap IntStream, Stream String ).

  • flatMap , "" .

  • , collect .

+5

- :

 String[] A;
 String[] B;
 //...
 List<String> myList= Arrays.asList (A);
 List<String> myList2 = Arrays.stream(B).map(
    (x)->"*".equals(x) ? x : doSomethingWith(x))
    .collect(Collectors.toList());
 myList.addAll(myList2);
-2

Source: https://habr.com/ru/post/1692092/


All Articles