Home > OS >  Adding elements to a HashMap Java
Adding elements to a HashMap Java

Time:03-24

I have a file which has names and numbers.

The file looks as follows :

  • Adam 250 321
  • John 120 431
  • Alex 200 200
  • Iris 121 221

is it possible to read from the file the elements in which the name is the key for numbers in the HashMap ?

for example Adam is the key for 250 and 321.

If possible could you please show me how it can be done ?

CodePudding user response:

Sure, first create a class to hold the numerical values, this is usually called a Tuple.

public class Tuple<T, R> {
    private T valueA;
    private R valueB;

    public Tuple(T value1, R value2) {
        valueA = value1;
        valueB = value2;
    }

    public T getValueA() {
        return valueA;
    }

    public R getValueB() {
        return valueB;
    }

    @Override
    public String toString() {
        return "Tuple [valueA="   valueA   ", valueB="   valueB   "]";
    }
}

Then read your file and place into the map.

public static void main(String[] args) {
    Map<String, Tuple<Integer, Integer>> map = new HashMap<>();
    
    try(BufferedReader reader = new BufferedReader(new FileReader("/your/file/location"))) {
        String line = reader.readLine();
        while (line != null) {
            String [] values = line.split("\\s");
            map.put(values[0], new Tuple<Integer, Integer>(Integer.valueOf(values[1]), Integer.valueOf(values[2])));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  •  Tags:  
  • java
  • Related