Home > Enterprise >  (Java) how to split an array by a certain value (string)?
(Java) how to split an array by a certain value (string)?

Time:11-07

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

CodePudding user response:

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.

CodePudding user response:

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();
  • Related