使用List和Map存放多个图书信息,遍历并输出。
其中商品属性:编号,名称,单价,出版社;使用商品编号作为Map中的key。
import java.util.*;
/*
使用List和Map存放多个图书信息,遍历并输出。
其中商品属性:编号,名称,单价,出版社;使用商品编号作为Map中的key。
*/
public class Test1 {
public static void main(String[] args) {
ArrayList<Goods> list = new ArrayList<>();
Goods goods1 = new Goods(1, "1", 1, "001");
Goods goods2 = new Goods(2, "2", 2, "002");
Goods goods3 = new Goods(3, "3", 3, "003");
Goods goods4 = new Goods(4, "4", 4, "004");
list.add(goods1);
list.add(goods2);
list.add(goods3);
list.add(goods4);
Iterator<Goods> iterator = list.iterator();
while (iterator.hasNext()) {
Goods next = iterator.next();
System.out.println(next);
}
System.out.println("========================================");
for (Goods i : list) {
System.out.println(i);
}
System.out.println("==========================================");
HashMap<Integer, Goods> map = new HashMap<>();
Goods good1 = new Goods(1, "1", 1, "001");
Goods good2 = new Goods(2, "2", 2, "002");
Goods good3 = new Goods(3, "3", 3, "003");
Goods good4 = new Goods(4, "4", 4, "004");
map.put(1,good1);
map.put(2,good2);
map.put(3,good3);
map.put(4,good4);
Set<Map.Entry<Integer, Goods>> entries = map.entrySet();
for (Map.Entry<Integer, Goods> keyValue : entries){
Integer key = keyValue.getKey();
Goods value = keyValue.getValue();
System.out.println(key+":"+value);
}
}
}
假如有以下email数据“aa@sohu.com,bb@163.com,cc@sina.com”
现需要把email中的用户部分和邮件地址部分分离,分离后以键值对应的
方式放入HashMap?
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/*
假如有以下email数据“aa@sohu.com,bb@163.com,cc@sina.com”
现需要把email中的用户部分和邮件地址部分分离,分离后以键值对应的
方式放入HashMap?
*/
public class Test2 {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
String s = "aa@sohu.com,bb@163.com,cc@sina.com";
String[] strings = s.split(",");
for (String youxiang : strings){
String[] strings1 = youxiang.split("@");
String name = strings1[0];
String address = strings1[1];
map.put(name,address);
}
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> keyValue : entries){
String name = keyValue.getKey();
String address = keyValue.getValue();
System.out.println(name+":"+address);
}
}
}