我有一个包含名字和姓氏,年龄,电子邮件,性别,城市和州的字符串数组。我应该使用ArrayList和哈希映射来计算生活在每个州的人数,并按升序打印。这是我到目前为止的内容:
我使用ArrayList来创建对象并将其放入其中。在我的哈希图中,我需要为每个州都有一个密钥和数组列表,其中将包含居住在那里的用户
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainPart1 {
public static void main(String[] args) {
List<User> listOfUsers = new ArrayList<>();
HashMap<String, ArrayList<User>> hmap = new HashMap<>();
for (String str : Data.users) {
String[] userData = str.split(",");
User newUser = new User(userData[0], userData[1], Integer.parseInt(userData[2]), userData[3], userData[4], userData[5], userData[6]);
listOfUsers.add(newUser);
}
for (String str : Data.otherUsers) {
String[] userData = str.split(",");
User newUser = new User(userData[0], userData[1], Integer.parseInt(userData[2]), userData[3], userData[4], userData[5], userData[6]);
listOfUsers.add(newUser);
}
ArrayList<User> list;
for (int i = 0; i < listOfUsers.size(); i++) {
String key = listOfUsers.get(i).getState();
if (hmap.containsKey(key)) {
list = hmap.get(listOfUsers.get(i).getState());
}
else {
list = new ArrayList<>();
}
list.add(listOfUsers.get(i));
hmap.put(key, list);
}
System.out.println("State: Count:");
for (String key : hmap.keySet()) {
System.out.print(key + "\t\t\t ");
System.out.println(hmap.get(key).size());
}
}
}
公共类用户{
private String firstName;
private String lastName;
private int age;
private String email;
private String gender;
private String city;
private String state;
public User(String firstName, String lastName, int age, String email, String gender, String city, String state) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.email = email;
this.gender = gender;
this.city = city;
this.state = state;
}
public String getFirstname() {
return firstName;
}
public void setFirstname(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return firstName + "," + lastName + "," + age + "," + email + "," + gender + "," + city + "," + state;
}
}
我能够使用数组列表将对象放入哈希图中,但是我无法使其按升序工作