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.
>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]