java中List转Map以及map遍历的四种⽅式
原⽂地址:
⽅便⾃⼰查看,所以拷了⼀份到⾃⼰这边,⽅便查
Java8List转map分组
Java8List转map分组此处是根据名称作为key 分组
public Map<String, List<Student>> groupList(List<Student> students) {
Map<String, List<Student>> map = students.stream().upingBy(Student::getName));
return map;
}
在java中所有的map都实现了Map接⼝,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以⽤以下的⽅式去遍历。
⽅法⼀:在for循环中使⽤entries实现Map的遍历:
/**
* 最常见也是⼤多数情况下⽤的最多的,⼀般在键值对都需要使⽤
*/
Map <String,String>map = new HashMap<String,String>();
map.put("熊⼤", "棕⾊");
map.put("熊⼆", "黄⾊");
for(Map.Entry<String, String> entry : Set()){
String mapKey = Key();
String mapValue = Value();
System.out.println(mapKey+":"+mapValue);
}
⽅法⼆:在for循环中遍历key或者values,⼀般适⽤于只需要map中的key或者value时使⽤,在性能上⽐使⽤entrySet较好;
Map <String,String>map = new HashMap<String,String>();
map.put("熊⼤", "棕⾊");
map.put("熊⼆", "黄⾊");
//key
for(String key : map.keySet()){
System.out.println(key);
}
//value
for(String value : map.values()){
System.out.println(value);
}
⽅法三:通过Iterator遍历:
Iterator<Entry<String, String>> entries = Set().iterator();
while(entries.hasNext()){
Entry<String, String> entry = ();
String key = Key();
String value = Value();
System.out.println(key+":"+value);
}
⽅法四:通过键值遍历,这种⽅式的效率⽐较低,因为本⾝从键取值是耗时的操作:
for(String key : map.keySet()){
String value = (key);
System.out.println(key+":"+value);
}
list转map在Java8中stream的应⽤
利⽤Map⽅法进⾏转换 <k,v>
public Map<Long, String> getIdNameMap(List<Account> accounts) {
//key不会重复时候
return accounts.stream().Map(Account::getId, Account::getUsername));
//key重复的时
return accounts.stream().Map(Account::getId, Account::getUsername, (key1, key2) -> key2));
}
收集对象实体本⾝
在开发过程中我们也需要有时候对⾃⼰的list中的实体按照其中的⼀个字段进⾏分组(⽐如 id ->List)这时候要设置map的value值是实体本⾝。
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().Map(Account::getId, account -> account));
}
account -> account是⼀个返回本⾝的lambda表达式,其实还可以使⽤Function接⼝中的⼀个默认⽅法 Function.identity(),这个⽅法返回⾃⾝对象,更加简洁重复key的情况。在list转为map时,作为key的值有可能重复,这时候流的处理会抛出个异常:Java.lang.IllegalStateException:Duplicate key。这时候就要在toMap⽅法中指定当key冲突时key的选择。(这⾥是选择第⼆个key覆盖第⼀个key)
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().Map(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
⽤groupingBy 或者 partitioningBy进⾏分组根据⼀个字段或者属性分组也可以直接⽤groupingBy⽅法,很⽅便
Map<Integer, List<Person>> personGroups = ate(new PersonSupplier()).
limit(100).
upingBy(Person::getAge));
Iterator it = Set().iterator();
while (it.hasNext()) {
Map.Entry<Integer, List<Person>> persons = (Map.Entry) it.next();
System.out.println("Age " + Key() + " = " + Value().size());
}
统计
Map<Stirng,Long> overflowMap = ?
if (CommonUtil.List())){
overflowMap =List().stream().upingBy(SmartDeviceDTO::getNzbm, unting())); }
BigDdecimal 的求和
BigDecimal result2 = userList.stream()
// 将user对象的age取出来map为Bigdecimal
.map(User::getAge)
// 使⽤reduce()聚合函数,实现累加器
.reduce(BigDecimal.ZERO,BigDecimal::add);
获取json中的key
/**
* 递归读取所有的key
*
* @param jsonObject
*/
public static StringBuffer getAllKey(JSONObject jsonObject) {
StringBuffer stringBuffer = new StringBuffer();
Iterator<String> keys = jsonObject.keySet().iterator();// jsonObject.keys();
while (keys.hasNext()) {
String key = ();
stringBuffer.String()).append("|");
if ((key) instanceof JSONObject) {
JSONObject innerObject = (JSONObject) (key);
stringBuffer.append(getAllKey(innerObject));
} else if ((key) instanceof JSONArray) {
JSONArray innerObject = (JSONArray) (key);
stringBuffer.append(getAllKey(innerObject));
}
java数组字符串转数组}
return stringBuffer;
}
java 遍历Map及Map转化为⼆维数组的实例
int a = 0, b = 0, c = 0;
/
/ 第⼀种:通过Map.keySet()遍历Map及将Map转化为⼆维数组
Map<String, String> map1 = new HashMap<String, String>();
map1.put("012013012013", "张三");
map1.put("012013012014", "张四");
String[][] group1 = new String[map1.size()][2];
System.out.println("第⼀种:通过Map.keySet()遍历map1的key和value");
for (String key : map1.keySet()) {
System.out.println("key = " + key + " and value = " + (key));
group1[a][0] = key;
group1[a][1] = (key);
a++;
}
System.out.println("map1.size()为:" + map1.size() + ",a为:" + a + ",group1数组的长度为:" + group1.length);
System.out.println("----------------------------------------------------");
for(int n = 0; n < group1.length; n++) {
System.out.println("key = " + group1[n][0] + " and value = " + group1[n][1]);
}
// 第⼆种:通过Set()使⽤iterator()遍历Map及将Map转化为⼆维数组
Map<String, String> map2 = new HashMap<String, String>();
map2.put("112013012013", "李三");
map2.put("112013012014", "李四");
System.out.println("\n" + "第⼆种:通过Set()使⽤iterator()遍历map2的key和value");
Iterator<Map.Entry<String, String>> iterator = Set().iterator();
String[][] group2 = new String[map2.size()][2];
while (iterator.hasNext()) {
Map.Entry<String, String> entry = ();
System.out.println("key = " + Key() + " and value = " + Value());
group2[b][0] = Key();
group2[b][1] = Value();
b++;
}
System.out.println("map2.size()为:" + map2.size() + ",b为:" + b + ",group2数组的长度为:" + group2.length);
System.out.println("----------------------------------------------------");
for(int n = 0; n < group2.length; n++) {
System.out.println("key = " + group2[n][0] + " and value = " + group2[n][1]);
}
// 第三种:通过Set()遍历遍历Map及将Map转化为⼆维数组
Map<String, String> map = new HashMap<String, String>();
map.putAll(map1);
map.putAll(map2);
String[][] group3 = new String[map.size()][2];
System.out.println("\n" + "第三种:通过Set()遍历map的key和value ");
for (Map.Entry<String, String> entry : Set()) {
System.out.println("key = " + Key() + " and value = " + Value());
group3[c][0] = Key();
group3[c][1] = Value();
c++;
}
System.out.println("map.size()为:" + map.size() + ",c为:" + c + ",group3数组的长度为:" + group3.length);
System.out.println("----------------------------------------------------");
for(int n = 0; n < group3.length; n++) {
System.out.println("key = " + group3[n][0] + " and value = " + group3[n][1]);
}
}
}
多字段分组
public static void main(String[] args) {
User user1 = new User("zhangsan", "beijing", 10);
User user2 = new User("zhangsan", "beijing", 20);
User user3 = new User("lisi", "shanghai", 30);
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
Map<String, List<User>> collect = list.stream().upingBy(e -> fetchGroupKey(e)));
//{zhangsan#beijing=[User{age=10, name='zhangsan', address='beijing'}, User{age=20, name='zhangs
an', address='beijing'}], // lisi#shanghai=[User{age=30, name='lisi', address='shanghai'}]}
System.out.println(collect);
}
private static String fetchGroupKey(User user){
Name() +"#"+ Address();
}
JSONObject与对象互转
//Javabean对象转换成String类型的JSON字符串
//String类型的JSON字符串转换成Javabean对象
/
/Json字符串转换成JSONObject对象
JSONObject.parseObject(JSON字符串)
//JSON字符串转换成Javabean对象
JSONObject.parseObject(JSON字符串,Javabean.class)
例如
Refund r = new Refund();
String jsonStr = JSONString(r);
String jsonStr = "{\"msg\":\"ZhangSan\"}";
Refund r = JavaObject(jsonStr,Refund.class);
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
Refund r = JSONObject.parseObject(jsonStr,Refund.class);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论