File contents:
Brown 1.44
Baxter 2.75
Peterson 2
Brown 3.14
Smith 6.6
Baxter 1.35
Peterson 3.1
Brown 2.02
Console output:
Baxter 4.1
Peterson 5.1
Brown 6.6
Smith 6.6
package com.codegym.task.task19.task1919;
/*
Calculating salaries
C:\Users\Администратор\CodeGymTasks\2.JavaCore\src\com\codegym\task\task19\file19.txt
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
List<String> list = new ArrayList<>();
try(BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
while (reader.ready()) list.add(reader.readLine());
}
Map<String, Double> map = new HashMap<>();
String[] part;
double salary;
for (String line : list) {
part = line.split("\\s+");
try {
if (!map.containsKey(part[0])) {
salary = Double.parseDouble(part[1]);
map.put(part[0], salary);
} else {
salary = Double.parseDouble(part[1]) + map.get(part[0]);
map.put(part[0], salary);
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
}
}
List<Person> personList = new ArrayList<>(map.size());
for (String key : map.keySet()) {
personList.add(new Person(key, map.get(key)));
}
Comparator<Person> compareBySalary = ((o1, o2) -> Double.compare(o1.salary, o2.salary));
Comparator<Person> compareByName = ((o1, o2) -> o1.name.compareTo(o2.name));
personList.sort(compareBySalary.thenComparing(compareByName));
for (Person person : personList)
System.out.println(person);
}
static class Person {
public String name;
public double salary;
public Person(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String toString() {
return name + " " + salary;
}
}
}
/*
Calculating salaries
The first parameter of the main method is a file name.
Each line of the specified file has the following format:
name value
where [name] is a String and [value] is a double. [name] and [value] are separated by a space.
Find the sum of all the values for each name.
Display all the data, sorted by name in ascending order.
Close the streams.
Example input file:
Peterson 2
Smith 6
Baxter 1.35
Peterson 3.1
Example output:
Baxter 1.35
Peterson 5.1
Smith 6.0
Requirements:
1. The program must NOT read data from the console.
2. The program must read the file's contents (use FileReader).
3. The file input stream (FileReader) must be closed.
4. The program should write to the console each name, sorted in ascending order, and the sum of all its values.
*/