class MapManager2 {
public static Map readData(String fileName) {
Map mapOfData;
Map sortedByValue = null;
try {
Scanner file = new Scanner(new File(fileName)); // read file
mapOfData = new TreeMap(); // create Map to store the values
while (file.hasNextLine()) {
String line = file.nextLine(); // read the line
String[] words = line.split("\\s+"); // split the item and price by space
Double price = Double.parseDouble(words[1]); // parse the double price
mapOfData.put(words[0], price); // put the data in map
}
/* Sort the map on basis of value*/
sortedByValue = mapOfData.entrySet()
.stream().sorted((Map.Entry.comparingByValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
} catch (FileNotFoundException e) {
System.out.println("Input file not found");
}
return sortedByValue;
}
}
public class Problem21 {
public static void main(String[] args) {
Map map = MapManager2.readData("input.txt");
if (map == null) {
System.out.println("Input file not found.");
return;
}
System.out.println(map);
}
[code]System.out.println(map); [/code] результат: {A=2, B=4, C=5 .. но я хочу распечатать [code]A 2 B 4 C 5 ... [/code] Итак, подсказка моего процессора — переопределение карты toSting(), но я не понимаю это мой код р> [code]class MapManager2 { public static Map readData(String fileName) { Map mapOfData; Map sortedByValue = null;
try { Scanner file = new Scanner(new File(fileName)); // read file mapOfData = new TreeMap(); // create Map to store the values
while (file.hasNextLine()) { String line = file.nextLine(); // read the line String[] words = line.split("\\s+"); // split the item and price by space Double price = Double.parseDouble(words[1]); // parse the double price mapOfData.put(words[0], price); // put the data in map }
/* Sort the map on basis of value*/ sortedByValue = mapOfData.entrySet() .stream().sorted((Map.Entry.comparingByValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); } catch (FileNotFoundException e) { System.out.println("Input file not found"); } return sortedByValue; }
} public class Problem21 { public static void main(String[] args) { Map map = MapManager2.readData("input.txt"); if (map == null) { System.out.println("Input file not found."); return; } System.out.println(map); } [/code]