how to tell part of an arraylist's content

2

What I want is to count the number of workers who have a certain type of char  such as those that are of type 'P' and those that are of type 'R'

 List<Trabajador> trabajadores = new ArrayList<Trabajador>();

        trabajadores.add(new Trabajador("t0001","37546352", "Carlos", "Diaz", "Analista Programador", 26, 3000.0, 'P'));
        trabajadores.add(new Trabajador("t0002","37553452", "Oscar ", "Rodriguez", "Contador", 22, 2500.0, 'P'));
        trabajadores.add(new Trabajador("t0003","37685672", "Cesar", "Carmelo", "Gerente", 40, 1500.0, 'P'));
        trabajadores.add(new Trabajador("t0004","38956252", "Josue", "Cardenaz", "Practicante", 35, 850.0, 'R'));
        trabajadores.add(new Trabajador("t0005","94523442", "Richard", "Acosta", "Tecnico", 36, 1800.0, 'R'));   


        em.setTrabajadores(trabajadores);
    
asked by Lrawls 22.10.2016 в 03:29
source

1 answer

3

If you want to count items from your List for a given attribute of your class Trabajador from Java8 you could use Stream using groupingBy from the class Collectors to group them by attribute. and a Map to store clave and valor

/* Tomando en cuenta que tu valor a comparar es un Character, long es
 el valor devuelto por counting , getValue será su getter del atributo char*/ 
Map<Character, Long> t=  
trabajadores.stream().collect(
Collectors.groupingBy(Trabajador::getValue, Collectors.counting()));

System.out.println(t);

Or a simple method going through Lista and comparing each of them

int Counting(List<Trabajador> lista,char a)
{
    int count=0;
    for (Trabajador pe: lista) {
        if(String.valueOf(pe.getValue()).toLowerCase().
           equals(String.valueOf(a).toLowerCase()))
            count+=1;
    }
    return count;
}
System.out.println(Counting(trabajadores, 'A'));
    
answered by 22.10.2016 / 05:11
source