Use of the split method

3

Good morning, excuse my ignorance by simple doubt. I'll get right to the point.

I have a list of alerts

List<Alertas> alertas;

This list contains several messages sent to some users, I have the following methods that I can use:

getUsers_receive;
getMsg;

This is my database:

TheideaisthatIcanonlydisplaythemessageiftheperson'suserisin"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 comma-separated, so 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 some of these users I encounter a certain user.

Currently what I have is just that:

for (Alertas a : lista_alertas) {
    String[] usrs = a.getUsers_receive().split(",");
}
    
asked by anonymous 15.08.2016 / 14:08

3 answers

3

You can do something simpler. Use the String.IndexOf method, it returns the position of the desired String in another String , and when it does not find returns -1.

Boolean existe = (a.getUsers_receive().IndexOf(usuario) >= 0);

Source: link

    
15.08.2016 / 14:50
2

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

 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 do not know if it's the right way, but it worked.

    
15.08.2016 / 14:30
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 String into a Stream using the Pattern class. The code then checks to see 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

    
16.08.2016 / 17:05