目录
3.【String、Date、Timestamp、Long(ms)】的转换
其他知识点: ------------------- 分割线 ------------------
1.如果遇到需要Arrays$ArrayList转java.util.ArrayList,用Arrays.asList()是Arrays$ArrayList构造。
14.List转List 或 将JSON中某个JSONArray属性的JSONObject集合打平
note:JSONObect不是有序的,需要有序用LinkedHashMap
1.【String】和【List<String>】的转换
String 转 List<String>
String str="1,2,3,4";
List<String> list= StringUtils.isEmpty(str)?new ArrayList<>()
:new ArrayList<>(Arrays.asList(str.split(",")));
List<String> 转 String
//假设已有 List<String> list,内容为{12,3,5}
String s= String.join(",", list);
或
String s= StringUtil.listToString(list,",");
结果:
s:12,3,5
2.【Map】和【String】的转换
假设String="{1-2,2-2}";
map 转 String
String s = map.keySet().stream()
.map(key -> key + "-" + map.get(key))
.collect(Collectors.joining(", ", "{", "}"));
如果不需要大括号{}
String s = map1.keySet().stream()
.map(key -> key + "-" + map1.get(key))
.collect(Collectors.joining(", "));
String 转 map
Map<String, String> map = Arrays.stream(s.split(","))
.map(o-> o.split("-"))
.collect(Collectors.toMap(o-> o[0], o-> o[1]));
3.【String、Date、Timestamp、Long(ms)】的转换
Date 转 String
Date date = new Date();
SimpleDateFormat sdf1= new SimpleDateFormat("yyyy/MM/dd"));
String s=sdf1.format(date);
结果:
s:2021/09/02
String 转 Date
法1:
hutool的jar包,超好用 可以是任意时间的字符串格式
String dateStr = "2020-01-02"; //此处dateStr可以为任意的时间格式
Date date = DateUtil.parse(dateStr);
法2:
SimpleDateFormat sdf1= new SimpleDateFormat("yyyy/MM/dd"));
String s="2021/8/31";
Date d=sdf1.parse(s);
结果:
d:Tue Aug 31 00:00:00 CST 2021
------------------
当你想在java中写sql存入时间,需要将Date转为数据库支持的格式。Timestamp就可以为sql提供符合时间格式。
Long(ms) 转 Timestamp
Timestamp ts = new Timestamp(System.currentTimeMillis());
又如:
Long time = 1588137295000L;
Timestamp date = new Timestamp(time);
date输出:2020-04-29 13:14:55.0
Date 转 Timestamp
Date date = new Date();
Timestamp t=new Timestamp(date.getTime());
sql:
Timestamp date = new Timestamp(System.currentTimeMillis());
String.format("update student set update_time='%s' where id = %s", date, studentId);
Long(ms) 转 Date
Date date = new Date(System.currentTimeMillis());
又如:
Long time = 1588137295000L;
Date date = new Date(time);
date输出:Wed Apr 29 13:14:55 CST 2020
4.【String】和【JSONObject】的转换
Stirng 转 JSONObject
String s="{"name":["boy","girl"]}";
JSONObject json=JSONObject.parseObject(s);
JSONObject 转 String
String s = JSONObject.toJSONString(json);
6.【List】和【数组】的转换
List 转 数组(List<Long>转Long[ ] )
现有 List<Long> idList
Long[] long=templateIdList.toArray(new Long[idList.size()]);
long[] templateIdArr = ArrayUtils.toPrimitive(long);
List 转 数组(List<String>转String[ ])【多个String按指定切割规则切割,并将结果汇总成一个String】
List<String> list = Arrays.asList("zhe-shi-yi-shou","jian-dan-de-xiao-qing-ge");
List<String> results = list.stream().flatMap(o -> Arrays.stream(o.split("-"))).collect(Collectors.toList());
//输出:[zhe, shi, yi, shou, jian, dan, de, xiao, qing, ge]
数组 转 List
String[] strArray= new String[]{"A", "B", "C"};
List strList= Arrays.asList(strArray);
7.【List】和【JSONArray】的转换
List 转 JSONArray
List<T> list = new ArrayList<T>();
JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
JSONArray 转 List
//法1
JSONArray array= new JSONArray();
List<Student> list = JSON.parseArray(array.toJSONString(), Student.class);
/* 此处JSON.parseArray,JSONObject.parseArray,JSONArray.parseArray都行 */
//法2
JSONArray array= new JSONArray();
List<Student> list = array.toJavaList(Student.class);
8.【String】和【JSONArray】的转换
String 转 JSONArray
String st = "[{name:Tim,age:25,sex:male},{name:Tom,age:28,sex:male},
{name:Lily,age:15,sex:female}]";
JSONArray tableData = JSONArray.parseArray(st);
JSONArray 转 String
9.【数组】转【JSONArray】
JSONArray json = (JSONArray) JSONArray.toJSON(arr);
10.【JSONArray】转【Map】
JSONArray可能会转成两种格式,LinkedHashMap和JSONObject。为了保险起见,得区别对待
至于为什么会有两种格式,目前还不清楚。大佬们有知道的可以指点一下
JSONArrayjsonArray = new JSONArray();
jsonObject=new JSONObject();
jsonObject.put("name","张三");
jsonObject.put("email","243892");
jsonArray.add(jsonObject);
jsonArray.forEach(o->{
String email = null;
String name = null;
if (o instanceof LinkedHashMap) {
LinkedHashMap p = (LinkedHashMap) o;
email = (String) p.get("email");
realName = (String) p.get("name");
}else if (o instanceof JSONObject){
JSONObject p = (JSONObject) o;
email = p.getString("email");
realName = p.getString("name");
}
});
11.【JSONObject】和【Map】的转换
JSONObject 转 Map
JSONObject json=new JSONObject();
jsonObject.put("1",2);
jsonObject.put("2",2);
jsonObject.put("3",2);
HashMap<String, String> map = JSONObject.parseObject(json.toString(), HashMap.class);
Map 转 JSONObject
LinkedHashMap dataMap = (LinkedHashMap) response.getData();
JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(dataMap));
12.【String】转【Set】
String s = "1,2,3";
Set<String> set = new HashSet<>(Arrays.asList(templateIds.split(","));
13.【java对象】和【JSONObject】的转换
java对象 转 JSONObject
//假设有Student student = new Student中有数据
JSONObject json = (JSONObject) JSONObject.toJSON(student);
JSONObject 转 java对象
//假设o为JSONObject对象
Student s = JSONObject.parseObject(String.valueOf(o), Student.class);
14.【Map】和【List】的转换
map的key 转 List
note:通过该方式可以获得map的key排序后的值
List<String> list = map.entrySet().stream()
.map(o -> o.getKey()).collect(Collectors.toList());
//如果需要排序
Collections.sort(list);
//如果需要map按照key排序
LinkedHashMap<String, Integer> linkedHashMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey(String::compareTo))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
List的两属性转Map
note:如果需要对属性进行操作,请使用forEach遍历
Map<Integer, String> map = data.stream()
.collect(Collectors.toMap(Person::getAge, Person::getName));
15.【数组】和【Set】的转换
数组 转 Set
String[] strArray= new String[]{"A", "B", "C"};
Set<String> set = new HashSet<>(Arrays.asList(strArray));
set 转 数组
String[] arr = set.toArray(new String[0]);
16.【List】和【Set】的转换
List 转 Set
List<String> list = new ArrayList<>("A","B","C");
Set<String> result = new HashSet<>(list);
Set 转 List
//假设已有set,里头是A,B,C
Set<String> result = new HashSet<>(Array.asList("A","B","C"));
List<String> list = new ArrayList<>(result);
17.【java对象某一属性】转【List】
//假设已有student对象,里面有id字段
List<Long> ids = students.stream()
.map(o -> o.getId()).collect(Collectors.toList());
18. 【JsonArray属性】转【List】
idList = jsonArray.stream()
.map(o -> ((JSONObject) o).getLong("id")).collect(Collectors.toList());
19.【带分隔符字符串数组】转【List】
//假设字符串数组DayAndEpisode中是1-1,2-3,4-2
List<String> list= Arrays.stream(DayAndEpisode)
.map(o -> o.split("-")[0]).collect(Collectors.toList());
20.【枚举类】转【Map】
枚举类:TestEnum
public static HashMap<String,String> getEnumList() {
for (TestEnum testEnum : EnumSet.allOf(TestEnum.class)) {
HashMap<String, String> map = new HashMap<>();
map.put(testEnum.code.toString(),testEnum.name);
}
return map;
}
21.spring 【Jackson】 转【JSON】
Student stu = new Student(); //代转换对象
ObjectMapper mapper = new ObjectMapper();
try {
String s = mapper.writeValueAsString(stu);
JOSNObject json= JSON.parseObject(s);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
22.【Map】与【java对象】的转换
map 转 java对象
法1:(建议使用)
User user = JSON.parseObject(JSON.toJSONString(hashMap), User.class);
法2:
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "king");
map.put("sex", "男");
Student student = mapToJava(map, Student.class);
System.out.println("student = " + student);
}
public static <T> T mapToJava(Map<String, Object> map, Class<T> clazz) throws Exception {
if (map == null) {
return null;
}
T t = clazz.newInstance();
BeanUtils.populate(t, map);
return t;
}
java对象 转 map
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "king");
map.put("sex", "男");
// map 转 java对象
Student student = mapToJava(map, Student.class);
System.out.println("student = " + student);
// java对象 转 map
Map<?, ?> javaToMap = javaToMap(student);
System.out.println("javaToMap = " + javaToMap);
}
public static <T> T mapToJava(Map<String, Object> map, Class<T> clazz) throws Exception {
if (map == null) {
return null;
}
T t = clazz.newInstance();
BeanUtils.populate(t, map);
return t;
}
public static Map<?, ?> javaToMap(Object obj) {
if (obj == null) return null;
return new BeanMap(obj);
}
23.【字符串数组】转【String】
String[] cc = {"1","2"}
String s = Arrays.toString(cc);
//结果:s=12
24.【String】转【JSONArray】
String json = "[{\"name\":\"张三\",\"code\":\"1\"},{\"name\":\"李四\",\"code\":\"2\"}]";
JSONArray jsonArray = new JSONArray(json);
25.【List<Map>】转【List<JSONObject>】
List<Map<String, Integer>> list = new ArrayList<>();
List<JSONObject> list2 = list.stream().map(o -> JSON.parseObject(JSON.toJSONString(o))).collect(Collectors.toList());
∞.java对象按某属性分类,并收集另一属性转Map
Map<Long,List<Long>> idClassIdMap=studentList.stream()
.collect(Collectors.groupingBy(Student::getId
,Collectors.mapping(Student::getClassId,Collectors.toList())));
其他知识点: ------------------- 分割线 ------------------
1.如果遇到需要Arrays$ArrayList转java.util.ArrayList,用Arrays.asList()是Arrays$ArrayList构造。
解决方式:改变源数据的创建方式即可
List<String> idList = Arrays.stream(ids.split(","))
.collect(Collectors.toList());
2.List的交集、差集、并集
//假设:list1中有1,2,3,4,5,6。list2中有2,3,7,8
// 交集
List<String> list=list1.stream().filter(o-> list2.contains(o)).collect(Collectors.toList())
// 差集 (list1 - list2)
List<String> list=list1.stream().filter(o-> !list2.contains(o)).collect(Collectors.toList())
// 差集 (list2 - list1)
List<String> list=list2.stream().filter(o-> !list1.contains(o)).collect(Collectors.toList())
// 并集
List<String> listAll1 = list1.parallelStream().collect(Collectors.toList())
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList())
listAll.addAll(listAll2);
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList())
输出:
list.parallelStream().forEach(System.out :: println);
3.单List多属性去重
studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(o -> o.getStudentId() + "#" + o.getClassId()))), ArrayList::new));
4.双List多属性去重
//旧数据唯一索引key集合
List<String> peopleOldKey = peopleListOld.stream()
.map(o -> o.getPeopleId() + "#" + o.getPeopleName() + "#" + o.getPeopleAge())
.distinct()
.collect(Collectors.toList());
//判断差集
List<Student> addPeopleList = peopleListNew.stream()
.filter(o -> !peopleOldKey.contains(o.getPeopleId() + "#" + o.getPeopleName() + "#" + o.getPeopleAge()))
.collect(Collectors.toList());
5.排序
(1)JSONArray按某属性排序
//假设已有resultData的JSONArray对象
//实现resultData按time排序
List<Object> sortedResultData = resultData.stream()
.sorted(Comparator.comparing(o -> ((JSONObject) o).getString("time")))
.collect(Collectors.toList());
resultData = JSONArray.parseArray(JSON.toJSONString(sortedResultData));
(2)List按属性排序
1)list具有单属性
正序:
list.stream().sorted();
逆序:
list.stream().sorted(Comparator.reverseOrder());
2)list具有多属性
正序:
list.stream().sorted(Comparator.comparing(Student::getAge));
或
list.sort(Comparator.comparing(Student::getAge));
逆序:
list.stream().sorted(Comparator.comparing(Student::getAge).reversed());
list.sort(Comparator.comparing(Student::getAge)).reversed());
多个字段逆序:
先按阶段时间逆序,再按创建时间逆序
list.sort(Comparator.comparing(Calandar::getStageTime).reversed()
.thenComparing(Calandar::getCreateTime,Comparator.reverseOrder()));
(3)Map按key排序
正序:
Map<String, List<Map.Entry<String, JSONArray>>> collect = collect.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
逆序:
Map<String, List<Map.Entry<String, JSONArray>>> collect = collect.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
(4)Map按value排序
正序:
Map<LocalDate, BigDecimal> map = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
逆序:
Map<LocalDate, BigDecimal> map = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
(5)Map按key的指定顺序排序
List<String> rules = Arrays.asList("d", "c", "a");
HashMap<String, String> map = new HashMap<>();
map.put("a", "1");
map.put("d", "2");
map.put("c", "3");
LinkedHashMap<String, String> result= map.entrySet().stream()
.sorted(Comparator.comparingInt(k -> rules.indexOf(k.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
result.entrySet().stream().forEach(c-> System.out.println(c.getKey()+" "+c.getValue()));
结果:
d 2
c 3
a 1
note:
Collectors.toMap()有三个签名:
1.Collects.toMap(Map.Entry::getKey, Map.Entry::getValue);
参数一是转化后的key,参数二是转化后的value,此方法下,发生碰撞会直接丢异常--------------------------------------------------------------------------------------------------------------------
2.Collects.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue);
参数一二同上,参数三是发生碰撞时保持旧值--------------------------------------------------------------------------------------------------------------------
3.Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)
参数一二三同上,最后一个是你想生成的Map结构,这里采用的是LinkedHashMap.如果想实现排序后仍然保持Map结构,那么LinkedHashMap是不错的选择。
(6)Java自定义对象按属性的指定顺序排序
List<String> levelSorted = Arrays.asList("S","A+","A","B+","B");
studentList.stream()
.sorted(Comparator.comparing(o -> levelSorted.indexOf(o.getLevel())))
(7)多属性字段排序(含null值)
Student s1 = new Student(123, null);
Student s2 = new Student(12, null);
Student s3 = new Student(2, "king");
List<Student> list = new ArrayList<>(Arrays.asList(s1, s2, s3));
//null值放最后
list.sort(Comparator.comparing(Student::getName,Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(Student::getId,Comparator.reverseOrder()));
//null值放最前
list.sort(Comparator.comparing(Student::getName,Comparator.nullsFirst(Comparator.naturalOrder())).thenComparing(Student::getId,Comparator.reverseOrder()));
结果:
【null值放最后】
[Student(id=2, name=king), Student(id=123, name=null), Student(id=12, name=null)]
【null值放最前】
[Student(id=123, name=null), Student(id=12, name=null), Student(id=2, name=king)]
(8)java对象的多属性值的指定排序
note:该方式的sorted内一定是该写法(完美的Stream结构,否则不生效)
要求学生表按名字、指定数学成绩顺序、指定语文成绩顺序排名
//数学成绩排序:S、A+、A、B
List<String> MathGradeSort= Arrays.asList("S", "A+", "A", "B");
//语文成绩排序:S、A、B
List<String> ChineseGradeSort= Arrays.asList("S", "A", "B");
studentList = studentList.stream().sorted(Comparator.comparing(Student::getName)
.thenComparing(student-> MathGradeSort.indexOf(student.getMathGrade()))
.thenComparing(student-> ChineseGradeSort.indexOf(student.getChineseGrade())))
.collect(Collection.toList());
6.JSONArray过滤后返回JSONArray
JSONArray json = jsonArray.stream()
.filter(o->((JSONObject) o)
.getInteger("id")==1).collect(Collectors.toCollection(JSONArray::new));
7.获取JSONObject对象的key集合
JSONObject obj = new JSONObject();
obj.put("key1", "1");
obj.put("key2", "2");
obj.put("key3", "3");
//获取key集合
Set<String> fields = obj.keySet();
8.两个数组合成一个
String[] both = (String[]) ArrayUtils.addAll(first, second);
9.List、JSONArray遍历删除对象(安全)
List遍历删除对象
note:仅基本数据类型及其包装类、string可以使用,其他引用对象使用remove后会清空整个对象
//假设list中有数据:
List<integer> = Arrays.asList(1,2,3,4);
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if ("d".equals(s)) {
iterator.remove();//使用迭代器删除
}
}
其他删除方式1:相同元素全部删除
List<String>list = new ArrayList<String>();
list.add("hello"); //向列表中添加数据
list.add("world"); //向列表中添加数据
list.add("java"); //向列表中添加数据
list.add("hello"); //向列表中添加数据
list.removeIf(o->o.equals("hello")); //移除指定元素
// 结果: 最后list中只剩下world和java
其他删除方式1:只删除第一个相同元素
List<String>list = new ArrayList<String>();
list.add("hello"); //向列表中添加数据
list.add("world"); //向列表中添加数据
list.add("java"); //向列表中添加数据
list.add("hello"); //向列表中添加数据
list.remove("hello"); //移除指定元素
// 结果 world、java、hello
JSONArray遍历删除对象
JSONArray array = new JSONArray();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
obj1.put("name":"king");
obj2.put("name":"Holmes");
Iterator<JSONObject> o = array.iterator();
while (o.hasNext()) {
JSONObject curObj = (JSONObject) o.next();
if(curObj.getIntValue("key") == "king") {
o.remove();
}
}
10.获取Map中的key集合
Map<Long,Student> map = new HashMap<>();
Set<Long> idSet = map.keySet();
11.获取Map中的value集合
Map<Long,Student> map = new HashMap<>();
List<Student> values = map.values().stream().collect(Collectors.toList());
12.获取多个list的笛卡尔积
1)如果list都没有数据,则返回结果为null列表
2)如果只有一个数据,则只返回结果为该数据
3)>1个数据,笛卡尔积
public static void main(String[] args) {
List<String> nameList = Arrays.asList("wang","bo","zhan");
List<String> phoneList = Arrays.asList("11","2","3");
List<String> highList = Arrays.asList("180","185","55");
List<String> descartesList = descartes(nameList , phoneList , highList);
descartesList.forEach(System.out::println);
}
public static List<String> descartes(List<String>... lists) {
List<String> tempList = new ArrayList<>();
for (List<String> list : lists) {
if (tempList.isEmpty()) {
tempList = list;
} else {
tempList = tempList.stream().flatMap(item -> list.stream().map(item2 -> item + " " + item2)).collect(Collectors.toList());
}
}
return tempList;
}
13.两个List合并成一个List,不修改原List
List<String> collect = Stream.of(listA, listB)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
14.List<JSONArray>转List<JSONObject> 或 将JSON中某个JSONArray属性的JSONObject集合打平
eg:
List<JSONObject> studentList =
dataList.stream().map(o -> o.getJSONArray("students"))
.flatMap(o -> o.stream()).map(o->((JSONObject) o))
.collect(Collectors.toList());
eg:
List<JSONObject> studentList = dataList.stream()
.flatMap(o -> o.getJSONArray("students").stream())
.collect(Collectors.toList());
15. String时间字符串比较大小
String s1="2022-11-22";
String s2="2022-11-21";
System.out.println(s1.compareTo(s2));//结果:1
System.out.println(s2.compareTo(s1));//结果:-1
相等时 结果是 0
16.获取List指定范围的元素集合
note:注意对List的元素集合size()进行判断
获取List前4个元素
List newList = list.subList(0, N);
获取List第N个到第M个元素
List newList = list.subList(N, M);
17.快速打印打印【数组、List】中的元素
快速打印数组中的所有元素
String [] arr= new String[]{"a", "b", "c"};
System.out.println(Arrays.toString(arr));
快速打印List集合中的所有元素
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(Arrays.toString(list.toArray()));
18.两个JOSNObject合并成一个
JSONObject one = new JSONObject();
one.put("one","pig");
JSONObject two = new JSONObject();
two.putAll(one);
System.out.println("two = " + two); //输出: two = {"one":"fish"}
19.两属性相乘后累加
假设求商品总价格
int sum += data.getValue().stream()
.filter(o -> o.getPrice() != null)
.filter(o -> o.getNum != null)
.mapToLong(o -> (o.getPrice() * o.getNum))
.reduce(0, Long::sum);
20.流中根据判断条件获取不同的数据
incomes = costIncomes.stream()
.sorted(Comparator.comparing((Function<CostIncome, Date>) o -> o.getStageTime() == null ? o.getCreateTime() : o.getStageTime()).reversed())
.collect(Collectors.toList());
note:JSONObect不是有序的,需要有序用LinkedHashMap
文章持续更新 2023.9.11