-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilterByAge.java
68 lines (64 loc) · 2.8 KB
/
FilterByAge.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package Lab;
import java.util.*;
public class FilterByAge {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
Map<String, Integer> nameAndAge = new LinkedHashMap<>();
Map<String,Integer> finalResult = new LinkedHashMap<>();
List<String> names = new ArrayList<>();
for (int i = 1; i <= n; i++) {
String input[] = scan.nextLine().split(", ");
String name = input[0];
int ageCurrentPerson = Integer.parseInt(input[1]);
nameAndAge.put(name, ageCurrentPerson);
names.add(name);
}
String condition = scan.nextLine(); // young,old
int age = Integer.parseInt(scan.nextLine()); // age < age > age
if (condition.equals("younger")) {
List<String> youngPeople = namesToBeAddedToYoungPeopleMAp(nameAndAge, age, names);
for (String name : youngPeople) {
int yearsYoung = nameAndAge.get(name);
finalResult.put(name, yearsYoung);
}
} else if (condition.equals("older")) {
List<String> oldPeople = namesToBeAddedToOldPeopleMAp(nameAndAge, age, names);
for (String name : oldPeople) {
int yearsOld = nameAndAge.get(name);
finalResult.put(name, yearsOld);
}
}
String [] format = scan.nextLine().split(" ");
// String command = format[0];// "name" "age" or "name age"
if(format.length == 1){
if(format[0].equals("name")) {
finalResult.entrySet().forEach(e -> System.out.printf("%s%n", e.getKey()));
}else if(format[0].equals("age")){
finalResult.entrySet().forEach(e -> System.out.printf("%s%n", e.getValue()));
}
}else{
finalResult.entrySet().forEach(e -> System.out.printf("%s - %d%n",e.getKey(),e.getValue()));
}
}
private static List <String> namesToBeAddedToYoungPeopleMAp (Map<String, Integer> nameAndAge, int age, List<String> names) {
List <String> sufficientAge = new ArrayList<>();
for (String name : names) {
int number = nameAndAge.get(name);
if (number <= age) {
sufficientAge.add(name);
}
}
return sufficientAge;
}
private static List <String> namesToBeAddedToOldPeopleMAp (Map<String, Integer> nameAndAge, int age, List<String> names) {
List <String> sufficientAge = new ArrayList<>();
for (String name : names) {
int number = nameAndAge.get(name);
if (number >= age) {
sufficientAge.add(name);
}
}
return sufficientAge;
}
}