在上一篇中,和大家交流了java常用数据结构的基础知识。现在与大家分享各类数据结构的遍历问题、转换问题。
一、遍历问题
(1) List的遍历问题(以ArrayList为例)
①通过迭代器遍历
public static void traverseArrayListByIterator(List list) {
long startTime = System.currentTimeMillis();
for (Iterator iterator= list.iterator();iterator.hasNext();) {
iterator.next();
}
long endTime = System.currentTimeMillis();
System.out.println("traverseArrayListByIterator:"+(endTime - startTime)+"ms.");
}
②通过索引值(随机访问)遍历
public static void traverseArrayListByRandomAccess(List list) {
long startTime = System.currentTimeMillis();
for(int i=0;i
}
long endTime = System.currentTimeMillis();
System.out.println("traverseArrayListByRandomAccess:"+(endTime - startTime)+"ms.");
}
③通过for-each循环遍历
public static void traverseArrayListByForeach(List list) {
long startTime = System.currentTimeMillis();
for (Object object : list) {
;
}
long endTime = System.currentTimeMillis();
System.out.println("traverseArrayListByForeach:"+(endTime - startTime)+"ms.");
}
效率测试:
(2)Map的遍历问题(以HashMap为例)
①通过entrySet()遍历
public static void traverseHashMapByEntryset(Map map) {
if (map == null) {
return;
}
Iterator iterator = map.entrySet().iterator();
long startTime = System.currentTimeMillis();
while(iterator.hasNext()) {
//Map.Entry entry = (Entry) iterator.next();
iterator.next();
}
long endTime = System.currentTimeMillis();
System.out.println("traverseHashMapByEntryset:"+(endTime - startTime)+"ms.");
}
②通过keySet()遍历
public static void traverseHashMapByKeyset(Map map) {
if (map == null) {
return;
}
Iterator iterator = map.keySet().iterator();
long startTime = System.currentTimeMillis();
while(iterator.hasNext()) {
iterator.next();
}
long endTime = System.currentTimeMillis();
System.out.println("traverseHashMapByKeyset:"+(endTime - startTime)+"ms.");
}
③通过value()遍历
public static void traverseHashMapByValue(Map map) {
if (map == null) {
return;
}
Collection collection = map.values();
Iterator iterator = collection.iterator();
//int key = 0;
long startTime = System.currentTimeMillis();
while (iterator.hasNext()) {
iterator.next();
}
long endTime = System.currentTimeMillis();
System.out.println("traverseHashMapByValue:"+(endTime - startTime)+"ms.");
}
效率测试:
(3)Set的遍历问题(以HashSet为例)
①通过迭代器遍历
public static void traverseHashSetByIterator(Set set) {
long startTime = System.currentTimeMillis();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
iterator.next();
}
long endTime = System.currentTimeMillis();
System.out.println("traverseHashMapByEntryset:"+(endTime - startTime)+"ms.");
}
②通过for-each遍历
public static void traverseHashSetByForeach(Set set) {
String[] arr = (String[]) set.toArray(new String[0]);
long startTime = System.currentTimeMillis();
for (String string:arr) {
string.length();
}
long endTime = System.currentTimeMillis();
System.out.println("traverseHashSetByForeach:"+(endTime - startTime)+"ms.");
}
效率测试:
(4)数组的遍历问题
①通过for循环遍历
//通过for循环遍历数组
System.out.print("通过for循环遍历数组:");
for(int i=0;i
}
System.out.println();
②通过foreach遍历
//通过foreach遍历数组
System.out.print("通过foreach遍历数组:");
for (String string : arr) {
System.out.print(string+" ");
}
System.out.println();
③通过工具类Arrays遍历
//通过工具类Arrays遍历数组
System.out.print("通过工具类Arrays遍历数组:");
System.out.print(Arrays.toString(arr));
System.out.println();
④通过迭代器遍历
List
System.out.print("通过迭代器遍历数组:");
for(String str:list){
System.out.print(str+" ");
}
System.out.println();
⑤通过stream()遍历数组
//通过stream()遍历数组
System.out.print("通过stream遍历数组:");
Arrays.asList(arr).stream().forEach(i->System.out.print(i+" "));
测试:
二.相互转换
(1)转为json格式
①数组转json
String[] arrs = {"金星","木星","水星","火星","土星","天王星","海王星","太阳"};
String jsonStr = null;
try {
JSONArray jsonObject = JSONArray.fromObject(arrs);
jsonStr = jsonObject.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(jsonStr);
②List转json
List
list.add("abcdefg");
list.add("hijklmn");
list.add("opqrst");
list.add("uvwxyz");
String jsonStr = null;
try {
JSONArray jsonObject = JSONArray.fromObject(list);
jsonStr = jsonObject.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(jsonStr);
③Map转json
Map
map.put("1", "testMap");
map.put("2", new User("嘻哈", 20, '女'));
String jsonStr = null;
try {
JSONObject jsonObject = JSONObject.fromObject(map);
jsonStr = jsonObject.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(jsonStr);
④对象转json
User user = new User("张三", 100, '男');
String jsonStr =null;
try {
JSONObject jsonObject = JSONObject.fromObject(user);
jsonStr = jsonObject.toString();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(jsonStr);
(2)json格式转为其他格式
①json转为List
方式一:
String arrayStr = "[{\"name\":\"嘿嘿\",\"age\":\"23\",\"sex\":\"男\"},{\"name\":\"哈哈\",\"age\":\"24\",\"sex\":\"女\"}]";
List
try {
JSONArray jsonArray = JSONArray.fromObject(arrayStr);
//转化为list
list = (List
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (User user : list) {
System.out.println("数组对象格式的json字符串转List:"+user);
}
方式二:
String arrayStr = "[{\"name\":\"嘿2嘿\",\"age\":\"23\",\"sex\":\"男\"},{\"name\":\"哈2哈\",\"age\":\"24\",\"sex\":\"女\"}]";
User[] users =null;
try {
JSONArray jsonArray = JSONArray.fromObject(arrayStr);
//转化为数组
users = (User[]) JSONArray.toArray(jsonArray, User.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (User user : users) {
System.out.println("数组对象格式的json字符串转list:"+user);
}
②json转为Map
String strObject="{\"first\":{\"name\":\"中国上海\",\"age\":\"23\",\"sex\":\"男\"}}";
JSONObject jsonObject = JSONObject.fromObject(strObject);
MyBean bean = new MyBean();
Map map = new HashMap<>();
map.put("first", User.class);
try {
bean = (MyBean) jsonObject.toBean(jsonObject, MyBean.class, map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("对象格式的json字符串转Map:"+bean.getFirst());
③json转为Object
方式一:
String jsonStr = "{\"name\":\"呵呵\",\"age\":\"25\",\"sex\":\"男\"}";
User user = new User();
try {
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
user = (User)JSONObject.toBean(jsonObject, User.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("对象格式的json字符串转对象:"+user);
方式二:
String arrayStr = "[{\"name\":\"嘻嘻\",\"age\":\"26\",\"sex\":\"男\"}]";
User user = new User();
try {
JSONArray jsonArray = JSONArray.fromObject(arrayStr);
Object object = jsonArray.get(0);
JSONObject jsonObject = JSONObject.fromObject(object);
user = (User)JSONObject.toBean(jsonObject, User.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("数组对象格式的json字符串转对象:"+user);
以上详述了java中数组、List、Map、Set等几种数据结构的遍历问题。编程实现了在web项目中常用的json数据格式与List、Map、java对象之间的相互转换。希望能对读者有所帮助,欢迎随时指正和交流。