Home > Software engineering >  How to split String based on a Char, if it is in an ArrayList?
How to split String based on a Char, if it is in an ArrayList?

Time:04-09

I have an arraylist with data structured like so:

        ArrayList<String> payments = new ArrayList<>();
        payments.add("Sam|gbp|10000.0");
        payments.add("John|usd|-100000.0");
        payments.add("Hannah|BTC|20.0");
        payments.add("Halim|btc|-50.0");

I would like to get each line, and then to do it's split, but it's not working.

 for (String payment : payments) {
                 String[] data = payment.split("|");
                 System.out.println(data[2]);
                 // Gives a list of characters.

}

How can I get each line to split and within each line, I can get the data out.

Forexample, to do a check of which currency is being used.

CodePudding user response:

The problem isn't related to the list. It's the split command. The argument isn't "Split on this string". The argument is actually a regular expression. And | is regular expression-ese for 'or', as in, either the thing to the left of me, or to the right of me. Given that there is nothing to its left and nothing to its right, it's identical to .split(""), i.e. gives a list of characters.

The solution is to write a regular expression that matches a | symbol: payment.split("\\|") will do it. As a general principle, payment.split(Pattern.quote("|")) also works - and is the generalized way to solve the problem: "I want to split on this exact text, regardless of what that text is" - ask the regex library to escape whatever needs escaping, using its quote method.

CodePudding user response:

First of all, you are triggering a Regex with your split parameter.

Correct use would be String[] data = payment.split("\\|");

Then, to get your currency, use System.out.println(data[1]);. List- and Array-Indices start with a 0, so your required second field is accessible with [1].

If you use Java 8, you could

List<String> btcUsers =
               payments
                        .stream()
                        .filter(
                                payment -> payment.split("\\|")[1]
                                        .toLowerCase(Locale.ROOT)
                                        .equals("btc"))
                       .toList();

Which results in

System.out.println(btcUsers);
[Hannah|BTC|20.0, Halim|btc|-50.0]

CodePudding user response:

You should keep in mind that split function take a pattern of regex and is not like PHP for example. So you need escape characters like below

String[] data = payment.split("\\|");

  • Related