Use of the split method

Asked

Viewed 386 times

3

Good morning guys, sorry my ignorance for the simple doubt. I’ll get right to the point.

I have a list of alerts

List<Alertas> alertas;

This list there are several messages sent to some users, in it I have the following methods that I can use:

getUsers_receive;
getMsg;

This is my database: Banco de dados

The idea is that I can only show the message if the person’s user is in "usrs_receive" so for this I need to scan the list I already have of "user_receive" and try to find the person’s user.

All users are separated by comma, so soon I know I can use Split to do this.

My difficulty lies in: Separate the user_received with the split and after that locate if in any of these users I find certain user.

Currently what I have is just this:

for (Alertas a : lista_alertas) {
    String[] usrs = a.getUsers_receive().split(",");
}
  • 2

    Vinicius, are you using Java version 8? I ask this because there are some cool tricks that can be done with Stream. Otherwise you are on the right path. You can try to scan the array usrs and see if any of the positions contain the current user. Alternatively, if you’re going to do the same thing over and over again for different users it might be worth building a HashSet with the content of usrs, so you can use the method contains which has constant amortized performance (it is faster than scanning the array).

  • I am using the 8 yes @Anthonyaccioly, I will search on Stream. Thank you!

3 answers

3

2

Workaround using Java 8 streams:

final Pattern p = Pattern.compile(",");
alertas.stream()
    .filter(a -> p.splitAsStream(a.getUsers_receive()).anyMatch("vinicius.candido"::equals))
    .map(Alertas::getMsg)
    .forEach(System.out::println);

The idea is to break the String in a Stream using the class Pattern. The code then checks if this alert contains an entry for the user in question. If yes the code extracts and prints the message.


Source: Soen - Stream: Filter on Children, Return the Parent

2

Good morning, I was able to solve it this way:

 for (Alertas a : lista_alertas) {
        String[] usrs = a.getUsers_receive().split(",");
        for (String usr : usrs) {
            if (usr.equals("vinicius.candido")) {
                System.out.println(a.getMsg());
            }

        }
    }

I don’t know if it’s the right way but it worked rsrsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.