I don't know, how to add list to hashmap in this way, that list is sorted and hashmap also will be sorted.
package pl.codegym.task.task19.task1919;
/*
Obliczanie wynagrodzeń
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static void main(String[] args) throws IOException {
String data = "";
String lastName = "";
Double value = 0.0;
HashMap<String, Double> map = new HashMap<>();
ArrayList<String> line = new ArrayList<>();
ArrayList<String> string = new ArrayList<>();
ArrayList<Double> doubles = new ArrayList<>();
FileReader fileReader = new FileReader(args[0]);
// FileReader fileReader =
// new FileReader("D:\\JAVA\\CodeGym\\CodeGymTasks\\2.JavaCore\\src\\File1.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((data = bufferedReader.readLine()) != null) {
line.add(data);
}
Collections.sort(line);
for (String l : line) {
try {
String[] array = l.split(" ");
lastName = array[0];
string.add(lastName);
// System.out.println(lastName);
value = Double.parseDouble(array[1]);
doubles.add(value);
// System.out.println(value);
map.put(lastName, 0.0);
} catch (NumberFormatException e) {
}
}
for (Map.Entry<String, Double> m : map.entrySet()) {
for (int i = 0; i < string.size(); i++) {
if (m.getKey().equals(string.get(i)))
m.setValue(m.getValue() + doubles.get(i));
}
}
// for (Character c : charList) {
// int count = charMap.containsKey(c) ? charMap.get(c) : 0;
// charMap.put(c, count + 1);
// }
for (Map.Entry<String, Double> n : map.entrySet()) {
System.out.print(n.getKey() + " ");
System.out.println(n.getValue());
}
fileReader.close();
bufferedReader.close();
}
}
/*
Obliczanie wynagrodzeń
Pierwszym parametrem metody main jest nazwa pliku.
Każdy wiersz określonego pliku ma następujący format:
name value
gdzie [name] to String, a [value] to double. [name] i [value] są oddzielone spacją.
Znajdź sumę wszystkich wartości dla każdego nazwiska.
Wyświetl wszystkie dane, posortowane według nazwisk w kolejności rosnącej.
Zamknij strumienie.
Przykładowy plik wejściowy:
Peterson 2
Smith 6
Baxter 1.35
Peterson 3.1
Przykładowy wynik:
Baxter 1.35
Peterson 5.1
Smith 6.0
Requirements:
1. Program NIE może wczytywać danych z klawiatury.
2. Program musi odczytywać zawartość pliku (użyj konstruktora FileReader).
3. Strumień wejściowy pliku (FileReader) musi zostać zamknięty.
4. Program powinien zapisywać w konsoli każde nazwisko, posortowane w kolejności
rosnącej oraz sumę wszystkich jego wartości.
*/