Role interpretation

Asked

Viewed 33 times

1

How does this function look without the for? cycle using Objectoutputstream?

private synchronized void adicionarListaContactosOnline(){
        Set<String> listaContactosOnline = new HashSet<String>();

        for(Map.Entry<String, ObjectOutputStream> mapa : utilizadores.entrySet()){
            listaContactosOnline.add(mapa.getKey());
        }

        Mensagem mensagem = new Mensagem();
        mensagem.setAccao(Accao.CONTACTOS_ONLINE);
        mensagem.setContactosOnline(listaContactosOnline);                                  

        for(Map.Entry<String, ObjectOutputStream> mapa : utilizadores.entrySet()){
            mensagem.setNomeClienteEnviaMensagem(mapa.getKey());
            try {
                System.out.println("Contacto Online: " + mapa.getKey());                
                mapa.getValue().writeObject(mensagem);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • @Cantoni as this function looks like with the other method of the previous question?

1 answer

3


Unlike that reply, in which case there is no way to remove the for loop, as you need to iterate over all users to create an object mensagem for each one.

The most you can do is avoid two loops on the same Hashmap, see below a modified version:

private synchronized void adicionarListaContactosOnline(){
        Set<String> listaContactosOnline = new HashSet<String>();

        for(Map.Entry<String, ObjectOutputStream> mapa : utilizadores.entrySet()){
            listaContactosOnline.add(mapa.getKey());

            Mensagem mensagem = new Mensagem();
            mensagem.setAccao(Accao.CONTACTOS_ONLINE);
            mensagem.setContactosOnline(listaContactosOnline);                                  
            mensagem.setNomeClienteEnviaMensagem(mapa.getKey());

            try {
                System.out.println("Contacto Online: " + mapa.getKey());                
                mapa.getValue().writeObject(mensagem);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Browser other questions tagged

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