reasonable_syam reasonable_syam - 21 days ago 5
Java Question

Filtering on Java Stream based on Index or last array value modification using lambda

I have array of String like mentioned in code below. I am eliminating double quote present in each element but I have to perform an additional operation on last Index as I know that there is additional double quote.

String array[] = new String[]{"\"Awesome Systems, Inc. - 357", "\"Awesome Systems, Inc - 357", "\"wpe_stage\""};
Arrays.stream(array).map((str) -> (str = str.trim())
.substring(1, str.length()))
.forEach(System.out::println);


What I am getting is an output like-

Awesome Systems, Inc. - 357
Awesome Systems, Inc - 357
wpe_stage"


The desired output is like-

Awesome Systems, Inc. - 357
Awesome Systems, Inc - 357
wpe_stage


How can I do this using stream functionality or lamda? Is there any way to select last index in stream or any filtering based on index is possible?

Answer

You could use replaceAll and replace all instances of the double quote in one go, provided they're either at the start or the end of the element:

Arrays
    .stream(array)
    .map((str) -> (str = str.trim()).replaceAll("^\"|\"$", ""))
    .forEach(System.out::println);

Output

Awesome Systems, Inc. - 357
Awesome Systems, Inc - 357
wpe_stage