0

I have 2 Arrays.

One Array has Strings, which i look for.

static String[] namesToLookFor = { "NR", "STAFFELNR", "VONDATUM"};

the otherArray has Strings, which i got from a *.csv file.

indexString = indexReader.readLine();
indexArray = indexString.split(";");

My Goal is to system.out.println() the Values which are the indexArray[] and NOT in the namesToLookFor[].

For example:

namesToLookFor = {"NR"};

indexArray = {"HELLO","NR"};


//Any Algorithm here...

So in this case"HELLO" should be printed out, since it is NOT in the namesToLookFor[] Array.

1
  • 1
    I'd suggest using a Set rather than an array, then you can difference the set objects Commented Jul 9, 2018 at 13:23

4 Answers 4

5

If you are using java8 you can do the following

List<String> list = Arrays.asList(namesToLookFor);
Arrays.stream(indexArray)
        .filter(item -> !list.contains(item))
        .forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

Comments

1

You could iterate over your indexArray and check for each element if its contained in your namesToLookFor Array:

    String[] namesToLookFor = {"NR"};

    String[] indexArray = {"HELLO","NR"};

    List<String> excludedNames = Arrays.asList(namesToLookFor);

    for(String s : indexArray) {
        if (!excludedNames.contains(s)) {
            System.out.println(s);
        }
    }

Will output only "HELLO".

1 Comment

Arrays.asList(namesToLookFor) inside loop will create many unwanted objects. You should place it before loop and reuse
1
// Put array into set for better performance
Set<String> namesToFilter = new HashSet<>(Arrays.asList("NR", "STAFFELNR"));
String[] indexArray = indexReader.readLine().split(";");

// Create list with unfiltered values and remove unwanted ones
List<String> resultList = new ArrayList<>(indexArray);
resultList.removeAll(namesToFilter);

// Do with result whatever you want
for (String s : resultList)
    System.out.println(s);

Comments

0

With Array you can use contains function but after converting it to be ArrayList, the contains function will check if the ArrayList contains a specific value.

for (int i =0; i<indexArray.length; i++) {
        if (!Arrays.asList(namesToLookFor).contains(indexArray[i])) 
            System.out.println(indexArray[i]);
    }

Comments

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.