一、将[1,2,3,4,5]转为”1->2->3->4->5”
List<Integer> list = Arrays.asList(1,2,3,4,5);String list2 = list.stream().map(String::valueOf).collect(Collectors.joining("->"));
List<Integer> list = Arrays.asList(1,2,3,4,5);String list2 = list.stream().map(i -> String.valueOf(i)).reduce((a,b)-> a+"->"+b).get();
二、类型转换
int[] 转为 List
int[] arr = new int[]{1,2,3,4,5};List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
int[] 转为 Integer[]
int[] arr = new int[]{1,2,3,4,5};Integer[] arr2 = Arrays.stream(arr).boxed().toArray(Integer[]::new);
List
转为int[] List<Integer> list = Arrays.asList(1,2,3,4,5);int[] arr = list.stream().mapToInt(Integer::valueOf).toArray();
List
转为Integer[] List<Integer> list = Arrays.asList(1,2,3,4,5);Integer[] arr = list.stream().toArray(Integer[]::new);//Integer[] arr = list.toArray(new Integer[0]);
integer[]转为int[]
Integer[] arr = new Integer[] {1,2,3,4,5};int[] arr2 = Arrays.stream(arr).mapToInt(Integer::valueOf).toArray();
integer[]转为List
Integer[] arr = new Integer[] {1,2,3,4,5};List<Integer> list = Arrays.stream(arr).collect(Collectors.toList());
String[]转List
String[] strs={"1","2","3"};List<String> list = Arrays.stream(strings).map(Integer::parseInt).collect(Collectors.toList());
list转String[]
List<Integer> list = Arrays.asList(1,2,3,4,5);String[] strArray = list.stream().map(String::valueOf).toArray(String[]::new);
三、map应用
使用Stream统计List里面相同字符的数量,并返回Map
List<Character> list = Arrays.asList('a','b','a','c','d','d','d');Map<Character,Integer> map = new HashMap<Character,Integer>();map =list.stream().collect(Collectors.toMap(x -> x ,x -> 1,(n1,n2)->n1+n2));map.forEach((key,value)->{System.out.println(key+":"+value);});
四、经典转化
数组字符串转为数组
String arrayStr = "[10,9,2,5,3,7,101,18]";int[] nums = Arrays.stream(arrayStr.replace("[", "").replace("]", "").split(",")).mapToInt(Integer::parseInt).toArray();System.out.println(Arrays.toString(nums));
