Search code examples
javaarraysstringstring-concatenation

Discard elements of a String Array matching a specific criterion and Join them together without using indices


I have a string array of full names with different surnames, i.e.

String[] tempArray = {"rakesh bhagat", "mayur suryavanshi", "prathamesh ambre", "akash tare", "abhi ingle", "rutvik patil"};

I want to create a new string of all names except one name, i.e.

temp = "rakesh bhagat, mayur suryavanshi, prathamesh ambre, akash tare, abhi ingle, rutvik patil";

So here I want to remove "mayur suryavanshi" from array without using index because I don't know index of that item, but I have certain condition like

if(tempArray[i].endsWith("suryawanshi")){}

Which I can use in for loop. I tried to make new string with removing those item in for loop

String result = joiner.toString();
        
String temp = null;
        
for (int i = 0; i < tempArray.length; i++) {
    if (tempArray[i].endsWith("suryavanshi")) {
        continue;
    }
    if (temp == null) {
        temp = tempArray[i];
    } else {
        temp = temp + ", " + tempArray[i];
    }
}

Solution

  • Avoid concatenating string in the loop, each concatenation str1 + str2 in a new string stored as a separate object. As the consequence of this, lots of intermediate strings which you don't need would be created.

    Use StringBuilder or other built-in mechanisms when you need to join together more than just a couple of strings.

    Collectors.joining()

    It can be done with Stream API using built-in Collector joning():

    String[] tempArray = {"rakesh bhagat", "mayur suryavanshi", "prathamesh ambre", "akash tare", "abhi ingle", "rutvik patil"};
        
    String result = Arrays.stream(tempArray)
        .filter(str -> !str.endsWith("suryavanshi")) // retain only elements which don't end with "suryavanshi"
        .collect(Collectors.joining(", "));
    

    StringJoiner

    Alternatively, you can use a so-called enhanced for-loop (also known as for-each) and StringJoiner :

    StringJoiner joiner = new StringJoiner(", ");
        
    for (String str : tempArray) {
        if (str.endsWith("suryavanshi")) continue;
        
        joiner.add(str);
    }
            
    String result = joiner.toString();