0

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?

5
  • 1
    Hint: relying on direct "indexing" within strings is typically not such a good idea. That makes your code very prone to changes within your input data. So: try to avoid that; instead write robust code ... like what Mena put down for you. Commented Nov 15, 2016 at 14:45
  • @GhostCat thanks :) Commented Nov 15, 2016 at 14:46
  • 1
    @Mena You wrote down what I would have written, too ... if I would know more about streams and would have been able to put it down in the same time ;-) ... so upvoting and cheering that content is the minimum I can do here! Commented Nov 15, 2016 at 14:53
  • 1
    @GhostCat yes, but I am partial to compliments, hence the thanks :D Also to be honest here I think stream/lambda knowledge can only take you this far. You cannot know the index of the current element without performing some serious acrobatics (and I'm not sure I'm actually accurate here), so a workaround is in order. Commented Nov 15, 2016 at 14:56
  • @GhostCat thanks for your valuable suggestion! Commented Nov 15, 2016 at 14:58

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

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.