3

i have a string array like this:

firstArray = {"1", "2", "3", "4" };

and i have second array like this:

secondArray = {"2", "5", "6", "7" };

if i want to stream with one element, i can do like this:

firstArray.stream()
    .filter(element -> !element.equals("2"))
    .forEach((element) -> {
        finalArrayList.add(element);
    }
);

how can i stream first array with second arrays all elements in java 8 ?

2
  • 2
    Use static Stream.concat(Stream, Stream) docs.oracle.com/javase/8/docs/api/java/util/stream/… Commented Oct 6, 2016 at 14:48
  • 1
    I don't understand the question. What do you want to achieve? What is the expected result here? Commented Oct 6, 2016 at 15:02

2 Answers 2

6

If you want to keep only elements of the first array that you don't have in the second array using the Stream API, you could do it like this:

List<String> result = Arrays.stream(firstArray)
    .filter(el -> Arrays.stream(secondArray).noneMatch(el::equals))
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

1

What exactly do you want to do? Get all the elements in the first array that are also present in the second array?

Like this:

String[] firstArray = {"1", "2", "3", "4"};
String[] secondArray = {"2", "5", "6", "7"};

List<String> finalArrayList = Arrays.stream(firstArray)
        .filter(element -> arrayContains(secondArray, element))
        .collect(Collectors.toList());

Using the following utility method:

public static <T> boolean arrayContains(T[] array, T element) {
    return Arrays.stream(array)
                 .filter(e -> e.equals(element))
                 .findFirst().isPresent();
}

Note: Instead of using forEach and adding the results to finalArrayList, use a collector. That's more pure, from a functional programming point of view.

edit - With Holger's tips (see his comment below):

public static <T> boolean arrayContains(T[] array, T element) {
    return Arrays.stream(array)
                 .anyMatch(e -> e.equals(element));
}

1 Comment

Mind the existence of anyMatch(predicate) which is to prefer over filter(predicate).findFirst().isPresent(). Besides, if you are only interested in the presence of a match, findAny() would be more appropriate than findFirst()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.