Problems grouping with ArrayList

1

Good evening everyone! It seems a lie that stuck in a very simple task, I have the following java code that consists of a simple constructor that contains an integer.

Yes or if I have to use Java 7 for the implementation.

List<Prueba> prueba = new ArrayList<Prueba>();
prueba.add(new Prueba(1,"Prueba"));
prueba.add(new Prueba(3,"Prueba1"));
prueba.add(new Prueba(2,"Prueba2"));
prueba.add(new Prueba(2,"Prueba2"));
prueba.add(new Prueba(1,"Prueba"));
System.out.println("#1 normal for loop");              
for (int i = 0; i < prueba.size(); i++) {                    
  System.out.println(prueba.get(i).getPrueba());
}

Well, I have a problem I need to group the repeated items and on the other hand count how many times the elements are repeated.

Any help? Thank you ! :)

    
asked by jc1992 06.03.2018 в 00:02
source

1 answer

1

The most convenient way to do that count is using a Map , where the key would be the attribute of the class Prueba for which you want to group (in our case the String ) and count the repetitions and the value would be the number of times that attribute is repeated (be clear that here what we are doing is grouped by any attribute, which we must be convinced that if it repeats indicates that it is the same test).

    Map<String, Integer> groupingMap = new HashMap<>();
    for (Prueba item : prueba) {
        Integer count = groupingMap.get(item.getPrueba());
        groupingMap.put(item.getPrueba(), count == null ? 1 : ++count);
    }
    
answered by 06.03.2018 / 00:23
source