Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading