1.使用Map接口的实现类完成员工工资(姓名–工资)的摸拟:
1)添加几条信息
2)列出所有的员工姓名
3列出所有员工姓名及其工资
4)删除名叫“Tom”的员工信息
5)输出Jack的工资,并将其工资加1000元(通过取值实现)
6)将所有工资低于1000元的员工的工资上涨20%(通过取值实现)
public static void test1(){
Map<String,Integer> map = new HashMap<>();
map.put("Tom",3600);
map.put("Jake",3000);
map.put("张三",5000);
map.put("李四",800);
Set<String> keys =map.keySet();
for (String key : keys) {
System.out.println("姓名:" + key);
}
for (String key : keys) {
int value = map.get(key);
System.out.println("姓名:" + key + " 工资:" + value);
}
map.remove("Tom");
System.out.println(map);
System.out.println(map.get("Jake"));
map.put("Jake", map.get("Jake")+1000);
System.out.println(map);
for (String key: keys) {
if (map.get(key)<1000){
map.put(key,(int)(map.get(key)*1.2));
}
}
System.out.println(map);
}
2.分析以下需求,并用代码实现:
(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
class Students{
private String name;
private int age;
public Students(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Students{" +
"姓名='" + name + '\'' +
", 年龄=" + age +
'}';
}
}
(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
(3)利用三种方式遍历Map集合中的内容
public static void test2(){
Map<Students,String> map = new HashMap<>();
map.put(new Students("张三",22),"驻马店");
map.put(new Students("李四",20),"郑州");
map.put(new Students("王五",23),"信阳");
Set<Students> keys =map.keySet();
Iterator<Students> it =keys.iterator();
while (it.hasNext()){
Students key = it.next();
String value =map.get(key);
System.out.println("学生:"+key+"城市:"+value);
}
//遍历Map 方式二 通过遍历所有的Value 遍历map
Collection<String > values =map.values();
for (String value :values){
System.out.println("城市:"+value);
}
//遍历Map 方式三 通过遍历所有的entry 遍历map
Set<Map.Entry<Students,String>> entries =map.entrySet();
for (Map.Entry<Students,String> entry:entries) {
Students key = entry.getKey();
String value = entry.getValue();
System.out.println("学生:"+key+"家乡="+value);
}
}
3.统计一个字符串中字母字符,数字字符出现的次数。(不考虑其他字符)
public static void test3() {
Scanner scan = new Scanner(System.in);
System.out.println("请输入字符串");
String st = scan.next();
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) >= '0' && st.charAt(i) <= '9') {
if (!map.containsKey(st.charAt(i))) {
map.put(st.charAt(i), 1);
} else {
map.put(st.charAt(i), map.get(st.charAt(i)) + 1);
}
}
if (st.charAt(i) >= 'A' && st.charAt(i) <= 'Z') {
if (!map.containsKey(st.charAt(i))) {
map.put(st.charAt(i), 1);
} else {
map.put(st.charAt(i), map.get(st.charAt(i)) + 1);
}
}
if (st.charAt(i) >= 'a' && st.charAt(i) <= 'z') {
if (!map.containsKey(st.charAt(i))) {
map.put(st.charAt(i), 1);
} else {
map.put(st.charAt(i), map.get(st.charAt(i)) + 1);
}
}
}
System.out.println(map);
}