You can see two variants using break statement and other using whileController public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); HashMap<Integer, String> myMap = new HashMap<>(); while(true){ Integer id; String name; String tempInteger; tempInteger = reader.readLine(); // String representation of an integer i will check if it is empty asAs it is read if(tempInteger.isEmpty()){ break; } id = Integer.parseInt(tempInteger); name = reader.readLine(); if(name.isEmpty()){ myMap.put(id , name); break; } myMap.put(id, name); } for(Map.Entry<Integer, String> pairs : myMap.entrySet()){ System.out.println(pairs.getKey() + " " + pairs.getValue()); } } }