项目中经常会遇到list转String,list转map,String转list等情况,特在这里记录一下。
1.list转String
将List集合转化为用符号隔开的String字符串,只要用StringUtils中的join就行。
String listToString= org.apache.commons.lang3.StringUtils.join(list, ",")
2.list转map
我们会常遇到将一个list按某个字段作为key转为map,如下面,按年龄转map,传统方法是直接做循环:
Map<Integer, List<Person>> map = new HashMap<>();
List<Person> list = new ArrayList<>();
Person person1 = new Person(20, "张三","男");
Person person2 = new Person(21, "李四","男");
Person person3 = new Person(32, "王五","男");
Person person4 = new Person(21, "刘六","男");
Person person5 = new Person(20, "田七","男");
Person person6 = new Person(32, "王八","男");
Person person7 = new Person(21, "阿狗","男");
Person person8 = new Person(20, "阿十","男");
list.add(person1);
list.add(person2);
list.add(person3);
list.add(person4);
list.add(person5);
list.add(person6);
list.add(person7);
list.add(person8);
for (Person person : list) {
map.put(person.getAge(), new ArrayList<>());
}
Map<Integer, List<Person>> map1 = new HashMap<>();
for (Map.Entry<Integer, List<Person>> entry : map.entrySet()) {
List<Person> userList = new ArrayList<>();
for (Person person : list) {
if (entry.getKey() == person.getAge()) {
userList.add(person);
}
}
map.put(entry.getKey(), userList);
userList = null;
}
}
但我还是推荐用Java8 的Stream来做,特别简单:
Map<Integer,List<Person>> map2=list.parallelStream().collect(Collectors.groupingBy(Person::getAge));
就一句话的事。Java8的Stream对集合的操作都挺好用的,下次抽时间来分享一下。
3.String数组转list
定义一个String数组,用Arrays.asList转:
String[] string = {"aa","bb","cc"};
List<String> stringToList= Arrays.asList(string);
4.带逗号String转list
1.转Integer类型list
String IntegerType="1,2,3";
List<Integer> IntegerResult = Arrays.asList(StringType.split(",")).stream().map(s ->Integer.parseInt(s.trim())).collect(Collectors.toList());
2.转String类型的list
String StringType="a,b,c";
List<String> StringResult = Arrays.asList(StringType.split(",")).stream().map(s ->s.trim()).collect(Collectors.toList());
未完待续。。。