How to draw up different repeated attributes?

0

Good day, I have a ArrayList with a series of data:

 => 158 => 158=> 158=> 158=> 158=> 172=> 217=> 217=> 222 => 222=> 22 => 222

How could you group the numbers 158 in a list, in another list the 172 , in another list the 217 and finally in another list the 222 ?.

Thank you in advance.

    
asked by devjav 06.04.2017 в 18:33
source

2 answers

1

Why do not you use a map:

ArrayList<Integer> myList; // ... inicializacion y otros
HashMap<Integer, Integer> myMap = new HashMap<Integer, MyObject>();

for(Integer i: myList){
    myMap.put(i, myMap.get(i) + 1);
}

// esto es para recorrer el mapa
Set<Integer> keys = map.keySet();
Integer[] array = keys.toArray(new Integer[keys.size()]);

for (Integer key:array){
    System.out.println("numero: " + key + " cantidad: " + myMap.get(key));
}

Well, this is the idea.

    
answered by 06.04.2017 в 18:52
1

I propose two solutions:

  • Yes in the list you know the number of groups that will be obtained. as in this case there are four lists, four lists are created to later go through the list and add depending on the value

    List<Integer> listone = new ArrayList<>();
    List<Integer> listtwo = new ArrayList<>();
    List<Integer> listthre = new ArrayList<>();
    List<Integer> listfour = new ArrayList<>();
    for (Integer item : lista) {
        switch(item){
            case 158: listone.add(item);break;
            case 172: listtwo.add(item);break;
            case 217: listthre.add(item);break;
            case 222: listfour.add(item);break;
            default: break;
        }
    }
    System.out.println(Arrays.toString(listone.toArray()));
    System.out.println(Arrays.toString(listtwo.toArray()));
    System.out.println(Arrays.toString(listthre.toArray()));
    System.out.println(Arrays.toString(listfour.toArray()));
    
  • If the number of groups to obtain is unknown in the list, a

  • answered by 06.04.2017 в 18:58