Check and edit a List

4

I have a List:

private List<Geracao> lista;

This list will be populated with data coming from a database:

lista = dao.findAll();

The findAll() method:

@SuppressWarnings("unchecked")
    @Override
    public List<Geracao> findAll() throws Exception {
        log.info("Encontrando todas as Gerações");
        return em.createQuery("from Geracao").getResultList();
    }

This data after being filled in lista will go to the screen (JSF). I would like to do a formatting in the text before going to the screen, example: I have an attribute called nome in class Geracao . How can I do to get the value that will come from the bank, edit and then play to lista ?

My final goal is that in the text that will come from the bank before going to the screen, do a check if there is a word x. If there is x in the text, x will be formatted, example as bold before going to the screen. Ex:

texto = texto.replace(palavra, "<b>"+palavra+"</b>");
    
asked by anonymous 17.11.2016 / 11:40

2 answers

2

You can try this:

final String palavraChave = "palavra";
final String trocaPalavraChave = "<b>palavra</b>";

List<Geracao> lista = dao.findAll().stream().forEach(geracao -> {
  if(geracao.getNome().contains(palavraChave)) {
    geracao.setNome(geracao.getNome().replaceAll(palavra, trocaPalavraChave));
  }
});

To access variables external to .stream().forEach() they must be immutable, final .

UPDATE

The code above was made based on the Java8 API, if you are using a lower version you can use foreach base:

final String palavraChave = "palavra";
final String trocaPalavraChave = "<b>palavra</b>";

List<Geracao> lista = dao.findAll();
for(Geracao geracao : lista) {
  if(geracao.getNome().contains(palavraChave)) {
    geracao.setNome(geracao.getNome().replaceAll(palavra, trocaPalavraChave));
  }
}

UPDATE

As I mentioned in the comment, you can treat several rules within the same for example:

List<Geracao> lista = dao.findAll();
for(Geracao geracao : lista) {
  regraDeNome(geracao);
  regraXYZ(geracao);
}

private void regraDeNome(Geracao geracao) {
  final String palavraChave = "palavra";
  final String trocaPalavraChave = "<b>palavra</b>";

  if(geracao.getNome().contains(palavraChave)) {
    geracao.setNome(geracao.getNome().replaceAll(palavra, trocaPalavraChave));
  }
}
private void regraXYZ(Geracao geracao) {
  // tratamento da regra
}
    
17.11.2016 / 12:22
1

You can use the dataTable's rowStyleClass and create a method for formatting or treating words.

<p:dataTable value="#{ManagedBeam.lista}" var="item"
rowStyleClass="#{ManagedBean.tratarPalavra(item)}"

and in the method:

public String tratarPalavra(Geracao g) {
    // lógica e tratamento...
    return String;
}
    
17.11.2016 / 13:08