引用对象数组类型转换
- String数组转Integer数组
String[] strIds = new String[]{"123","321","567"};
Integer[] ids = (Integer[]) ConvertUtils.convert(strIds, Integer.class);
Double[] ids = (Double[]) ConvertUtils.convert(strIds, Double.class);
Long[] ids = (Long[]) ConvertUtils.convert(strIds, Long.class);
注:支持数组与数组之间的直接转换,如String->Long String->Double
数组与List转换
public class User{
private Long id;
private String name;
//省略get,set....
}
String[] arrays = {"a", "b", "c"};
//数组转List
List list = Stream.of(arrays).collect(Collectors.toList());
//List转数组
String[] strings = list.stream().toArray(String[]::new);
//对象取值
String[] strings = list.stream().map(User::getName).toArray();
//对象取值,转型
String[] ids = (String[])ConvertUtils.convert(list.stream().map(User::getId).toArray(), String.class);
引用对象转值
- Long数组转long数组
Long[] longIds = new Long[]{123123L,321321L,56786L};
long[] ids = Arrays.stream(longIds).filter(Objects::nonNull).distinct().mapToLong(Long::longValue).toArray();
//String[] strIds = new String[]{"123","321","567"};
//long[] ids = Arrays.stream(strIds).filter(Objects::nonNull).distinct().mapToLong(Long::parseLong).toArray();
List转Map
public class User{
private Long id;
private String name;
//省略get,set....
}
//不能重复Key,值不能为空
Map map = list.stream().collect(Collectors.toMap(User::getId, User::getName));
//重载,不能重复Key,值可以为空
Map map = list.stream().collect(HashMap::new, (m,v)->m.put(v.getId(), v.getName()),HashMap::putAll);
//去重复取新值 Map值不能为空
Map map = list.stream().collect(Collectors.toMap(User::getId, User::getName,(oldValue,newValue)->newValue)));
//获取对象 Map值不能为空
Map map = list.stream().collect(Collectors.toMap(User::getId,Function.identity(),(oldValue,newValue)->newValue)));
//去重复取新值 过滤空
Map map = list.stream()
.filter(user->user.getId()!=null)
.filter(user->user.getName()!=null)
.collect(Collectors.toMap(User::getId, User::getName,(oldValue,newValue)->newValue)));
Map转List
public class User{
private Long id;
private String name;
//省略get,set....
}
//获取值
List userList = new ArrayList<>(userMap.values());
//获取键
List ids = new ArrayList(userMap.keySet());
//获取子元素
List names = userMap.values().stream().collect(ArrayList::new,(m,v)->m.add(v.getName()),ArrayList::addAll);
//获取子元素 + 过滤
List names = userMap.values().stream()
.filter(user->!user.getName().equals("admin"))
.collect(ArrayList::new,(m,v)->m.add(v.getName()),ArrayList::addAll);