1

I have a list of arrays

[Type 1970, Type 1981, Type 1985, Type 1999]
[Type 1985, Type 1970, Type 1985, Type 1999]
[Type 1999, Type 1981, Type 1985, Type 1970]
[Type 1981, Type 1985, Type 1999, Type 1970]
[Type 1985, Type 1970, Type 1981, Type 1999]

I would like to split up these arrays while only pulling a specific model type such as "Type 1999" and providing a count.

This is what I have came up with so far:

int counter = 0 
for(int i = 0; i < listOfTypes.length; i++){
String[] typesSearch = listOfTypes[i]
if(typesSearch != null) {
    if(typesSearch.equals("Type 1999")); {
counter++;
}
}

Ideally the output would be a new array with only a certain element

{Type 1999, Type 1999, Type 1999, Type 1999} and so forth

I think from here I can just use the length() to get a count of the elements inside this newly created array

1
  • typesSearch.equals("Type 1999") will always return false because one of them is a String[] and the other is a String. They can never be equal. Commented Nov 7, 2021 at 1:23

2 Answers 2

1

I guess you have 2-d array

    String[][] listOfTypes = {
            {"Type 1970", "Type 1981", "Type 1985", "Type 1999"},
            {"Type 1985", "Type 1970", "Type 1985", "Type 1999"},
            {"Type 1999", "Type 1981", "Type 1985", "Type 1970"},
            {"Type 1981", "Type 1985", "Type 1999", "Type 1970"},
            {"Type 1985", "Type 1970", "Type 1981", "Type 1999"}
    };

and to count the occurrance of Type 1999

    int counter = 0;
    for (String[] typesSearch : listOfTypes) {
        for (String str : typesSearch) {
            if ("Type 1999".equals(str)) {
                counter++;
            }
        }
    }

or using stream

    int counter = (int) Arrays.stream(listOfTypes)
            .flatMap(typesSearch -> Arrays.stream(typesSearch))
            .filter(str -> str.equals("Type 1999"))
            .count();
Sign up to request clarification or add additional context in comments.

Comments

0

I have no idea why you'd want that; your current code works fine and is efficient.

I guess you can do this:

int count = (int) Arrays.stream(listOfTypes)
  .filter(x -> x.equals("Type 1999"))
  .count();

If you prefer that style, knock yourself out. Performance-wise and readability wise it really makes no difference. Making an intermediate array with just the Type 1999 entries is however, quite expensive, relative to just counting at any rate. It's also more code. I have no idea why you think it's a better solution vs. just counting.

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.