1. 程式人生 > >java list轉String,list轉map,String陣列轉list,帶逗號String轉list

java list轉String,list轉map,String陣列轉list,帶逗號String轉list

專案中經常會遇到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());

未完待續。。。