HashMap shows me duplicate elements java

1

My question is How can I show only the records I have in my hashmap without repeating them? Ex: I have a arraylist<String> loaded with data, I also have a text file loaded with data inside.

  • File content .txt :

25, Argentina

45, SAN SALVADOR

32, VENEZUELA.

  • Content arraylist

25_ARGENTINA

45_SAN SALVADOR

How will you see if I load a map of my text file and compare the keys (two-digit numeric digits) with what I have in my arraylist should show me the matching countries to those keys, in this case it would be ARGENTINA and SAN SALVADOR

But instead of that I get:

Country: ARGENTINA

Country: ARGENTINA

Country: ARGENTINA

Country: null

Country: SAN SALVADOR

Country: SAN SALVADOR

I have a method that reads the text file, loads it in a String, then loads the stored in the String in a hashmap, before I go through the arraylist and get the two-digit digits and store it in keyArray :

 String keyArray;

public void leer(ArrayList<String> arrayList) {
        Map<String, String> mapaCodigosArchivo = new HashMap();

        //Recorremos el arrayList
            for (String nombreArchivo : arrayList) {
                String[] separador = nombreArchivo.split("_");
                String codPaises = separador[0];
                keyArray = codPaises;
            } 

        try {
            // Abrimos el archivo con la ruta especificada.
            FileInputStream fstream = new FileInputStream(new File("Paises.txt"));
            // Creamos el objeto de entrada
            DataInputStream entrada = new DataInputStream(fstream);
            // Creamos el Buffer de Lectura
            BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
            String contenido;
            // Leer el archivo linea por linea
            while ((contenido = buffer.readLine()) != null) {
                String[] separador = contenido.split(",");
                mapaCodigosArchivo.put(separador[0], separador[1]);
               //Imprimimos los resultados que coinciden con la clave de dos digitos.
                System.out.println("Sucursal: " + mapaCodigosArchivo.get(keyArray));
            }
            // Cerramos el archivo
            entrada.close();
        } catch (Exception e) { //Catch de excepciones
            System.err.println("Ocurrio un error: " + e.getMessage());
        }
    }

And researched but I do not give with the correct answer, I hope you can help me. Thanks again.

    
asked by Gerardo Ferreyra 03.09.2017 в 04:34
source

1 answer

0

If you use JDK 7+ you can try this code. If you use an earlier version, you should vary the way you read the map and make the comparisons.

A good option is to use keySet , which:

  

Returns an overview of the keys contained in a map. The   set is backed by the map, so the changes in the   map are reflected in the set, and vice versa. If the map is modified   while an iteration of the whole is in progress (except for   through the own elimination operation of the iterator), the   The results of the iteration are not defined. The set supports the   elimination of elements, which eliminates the corresponding correlation   of the map, through operations Iterator.remove , Set.remove ,    removeAll , retainAll and clear . Does not support operations add or    addAll .

Code:

String [] keyArray; //Lo definimos como array

public void leer(ArrayList<String> arrayList) {
        Map<String, String> mapaCodigosArchivo = new HashMap();

        try {
            // Abrimos el archivo con la ruta especificada.
            FileInputStream fstream = new FileInputStream(new File("Paises.txt"));
            // Creamos el objeto de entrada
            DataInputStream entrada = new DataInputStream(fstream);
            // Creamos el Buffer de Lectura
            BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
            String contenido;
            // Leer el archivo linea por linea
            while ((contenido = buffer.readLine()) != null) {
                String[] separador = contenido.split(",");
                mapaCodigosArchivo.put(separador[0], separador[1]);
               //Imprimimos los resultados que coinciden con la clave de dos digitos.
                System.out.println("Sucursal: " + mapaCodigosArchivo.get(keyArray));
            }


            //Recorremos el arrayList
            for (String nombreArchivo : arrayList) {
                String[] separador = nombreArchivo.split("_");
                String codPaises = separador[0];
                keyArray.add(codPaises); //Agregamos al array
            } 

            for(String key : mapaCodigosArchivo.keySet()) {
                if(keyArray.contains(key)) {
                    System.out.println("Sucursal: " + mapaCodigosArchivo.get(key));
                }
            }

            // Cerramos el archivo
            entrada.close();
        } catch (Exception e) { //Catch de excepciones
            System.err.println("Ocurrio un error: " + e.getMessage());
        }
    }

COMPLETE DEMO SIMULATING DATA

Since you are reading a text file, it is difficult to simulate the data. I have artificially created an array that would simulate the data extracted from your text file.

The code works perfectly. I think that if you adapt it in your context you can reach a definitive solution to the problem.

Código Ver Demo

import java.util.*;
import java.lang.*;
import java.util.Collections; 
import java.util.HashMap;
class Rextester
{  
    public static void main(String args[])
    {
        /*Creamos array de prueba*/
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("25_ARGENTINA");
        arrayList.add("45_SAN SALVADOR");

        leer(arrayList);

    }


    public static void leer(ArrayList<String> arrayList) {
        List<String> keyArray= new ArrayList<String>();
        Map<String, String> mapaCodigosArchivo = new HashMap<String, String>();
        Map<String, String> mapaFinal = new HashMap<String, String>();

        System.out.println("Array con los códigos: "+arrayList);


        for (String nombreArchivo : arrayList) {
                String[] separador = nombreArchivo.split("_");
                String codPaises = separador[0];
                keyArray.add(codPaises); //Agregamos al array
        } 

        System.out.println("Array con los códigos extraidos de arrayList: "+keyArray);


        /*Creamos array de prueba, ponemos repetidos a propósito*/
        ArrayList<String> arrayTexto = new ArrayList<String>();
            arrayTexto.add("25,Argentina");
            arrayTexto.add("45,SAN SALVADOR");
            arrayTexto.add("32,VENEZUELA");
            arrayTexto.add("25,ARGENTINA");
            arrayTexto.add("45,SAN SALVADOR");
            arrayTexto.add("32,VENEZUELA");
            arrayTexto.add("25,Argentina");

        System.out.println("Array simulado archivo de texto: "+arrayTexto);

        for (String paises : arrayTexto) {
                String[] separador = paises.split(",");
                String codPaises = separador[0];
                mapaCodigosArchivo.put(separador[0], separador[1]);
        }       

        System.out.println("Mapa códigos archivo: "+mapaCodigosArchivo);
        System.out.println("Mapa códigos archivo keySet: "+mapaCodigosArchivo.keySet());

        for(String key : mapaCodigosArchivo.keySet()) {
                if(keyArray.contains(key)) {
                    System.out.println("Sucursal: " + mapaCodigosArchivo.get(key));
                }
            }
    }
}

Resultado:

Array con los códigos: [25_ARGENTINA, 45_SAN SALVADOR]
Array con los códigos extraidos de arrayList: [25, 45]
Array simulado archivo de texto: [25,Argentina, 45,SAN SALVADOR, 32,VENEZUELA, 25,ARGENTINA, 45,SAN SALVADOR, 32,VENEZUELA, 25,Argentina]
Mapa códigos archivo: {45=SAN SALVADOR, 25=Argentina, 32=VENEZUELA}
Mapa códigos archivo keySet: [45, 25, 32]

---Esta es la salida esperada:

Sucursal: SAN SALVADOR
Sucursal: Argentina
    
answered by 03.09.2017 / 05:22
source