Take all elements that meet a condition

Asked

Viewed 61 times

2

I have some Vector:

public static Vector<Integer> id = new Vector<Integer>();
public static Vector<String> nome = new Vector<String>();
public static Vector<String> nascimento = new Vector<String>();
public static Vector<String> trabalho = new Vector<String>();
public static Vector<String> foto = new Vector<String>();
public static Vector<String> premios = new Vector<String>();

I am currently using the following code to fetch a value in these arrays:

if(where.equals("id"))
    key = Record.id.indexOf(Integer.parseInt(value));
else if(where.equals("nome"))
    key = Record.nome.indexOf(value);
else if(where.equals("nascimento"))
    key = Record.nascimento.indexOf(value);
else if(where.equals("trabalho"))
    key = Record.trabalho.indexOf(value);
else if(where.equals("foto"))
    key = Record.foto.indexOf(value);
else if(where.equals("premios"))
    key = Record.premios.indexOf(value);

The problem is that in the case, the indexOf finds only the first occurrence in the list, I want to get the index of all occurrences of an element, there is some native method of Java for this? Or just by using for and by putting the contents found in a new Vector?

  • Apparently, yes. You’ll have to use repetition loop to scan the entire Vector and find other duplicates.

  • If you’re using JDK 7, tell me I’ll give you another answer, I hope I’ve helped, and if I’ve already helped, don’t forget to dial as solved, good studies :)

1 answer

2


If you are using java 8, you can use the streams API and pass a predicate and return the elements that meet a certain condition, follow the code below:

public List<String> obtemFotos(String criterio) {
  return Record.fotos
    .stream()
    .filter(foto -> foto.equals(criterio))
    .collect(Collectors.toList())
}

It would be something along those lines, and you would do that for every collection of yours, I think you have a much better way of treating these Ectors on a case-by-case basis, but I’m not going to go into that because it’s outside the scope of that question.

  • I’m using Java 7 in development, but it’s to migrate to 8. But I did it with a for for the time being, while waiting for the answer.

  • All right, when you migrate, you can use this, it gets much better.

Browser other questions tagged

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