Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
How can I count how often an element from an ArrayList occurs in the another ArrayList?

I want to count how often an element from ArrayList "list1" occurs in the other ArrayList "list2".

I want this output:

A 2
B 0
C 1
D 2

I get this output:

A 0
B 0
C 0
D 69

Coud you please help me to do this? Thank you!

enter code here

    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    ArrayList<Character> list1 = new ArrayList<Character>();
    ArrayList<Character> list2 = new ArrayList<Character>();

    Collections.addAll(list1, 'A', 'B', 'C', 'D');
    Collections.addAll(list2, 'D', 'A', 'C', 'A', 'D');

    for (int i = 0; i < list1.size(); i++) {

        for (int j = 0; j < list2.size(); j++) {
            

            if (list1.get(i) == list2.get(j)) {
                map.put(list1.get(i), 1);
            } 
            
            if (list1.get(i) == list2.get(j) && (map.containsKey(list1.get(i)))) {
                map.replace(list1.get(i), list1.get(i) + 1);
            } 
            
            if (list1.get(i) != list2.get(j)) {
                map.put(list1.get(i), 0);
            }
            
        } 
    }

    
    System.out.println("Map: ");
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Use the method frequency, from Collection, namely:

    for (Character c : list1)
       map.put(c, Collections.frequency(list2, c));

    System.out.println("Map: ");
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }

If you are a fan of one liners :

    list1.forEach(c -> map.put(c, Collections.frequency(list2, c)));

Including the printing of the elements:

list1.forEach(c ->  System.out.printf("%s %d%n", c, Collections.frequency(list2, c)));

By the way, your original answer was almost correct, you just had to rethink a bite the conditionals, and their order:

 for (Character c1 : list1) {
    for (Character c2 : list2) {
        if(map.containsKey(c1) && c1 == c2 ){
           map.put(c1, map.get(c1) + 1);
        }
        else if (!map.containsKey(c1) && c1 != c2 ) {
            map.put(c1, 0);
        } 
        else if (!map.containsKey(c1) && c1 == c2) {
            map.put(c1, 1);
        } 
    } 
}

Another advice is, if you do not explicitly need the loop index, it is better to use the idiom for (Character c1 : list1) rather than for(int i = 0; i < list1.size(); i++). The first is cleaner, and less error-prone than the second version. Moreover, you can use the variable c1 instead of having to do list1.get(i) all the time.

over 4 years ago · Santiago Trujillo Relatório

0

You can use Stream API introduced in Java 8 to accomplish this task. Here is an example code which resolves the problem:

        final List<Character> list1 = new ArrayList<Character>();
        final List<Character> list2 = new ArrayList<Character>();

        Collections.addAll(list1, 'A', 'B', 'C', 'D');
        Collections.addAll(list2, 'D', 'A', 'C', 'A', 'D');

        final Map<Character, Integer> map = new HashMap<>();
        for (final Character c : list1) {
            final int occurrences = (int) list2.stream().filter(c::equals).count();
            map.put(c, occurrences);
        }

        System.out.println("Map: ");
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

Note: For this group of problems I recommend you to start the implementation with writing some unit tests.

over 4 years ago · Santiago Trujillo Relatório

0

A cleaner Java 8 solution without extra loops would be:

List<Character> list1 = Arrays.asList('A', 'B', 'C', 'D');
List<Character> list2 = Arrays.asList('D', 'A', 'C', 'A', 'D');
      
Map<Character, Integer> map = list1.stream()
                                   .collect(Collectors.toMap(
                                       c -> c, 
                                       c -> Collections.frequency(list2, c)
                                   ));

// print entire map
System.out.println(map);

// print formatted map
map.entrySet().forEach(e -> System.out.printf("%s %d%n", e.getKey(), e.getValue()));

If the specific task is to print the frequencies, the intermediate map can be skipped altogether :)

list1.stream()
     .map(c -> new StringBuilder()
                       .append(c).append(' ')
                       .append(Collections.frequency(list2, c))
     )
     .forEach(System.out::println);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda