简体   繁体   中英

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 lambda? Is there any way to select last index in stream or any filtering based on index is possible?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM