比较两个String字符串数组元素差异
1、工具类
package io.renren.common.utils; import org.apache.commons.lang3.ArrayUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @program: ivvdata-security * @description: 比较两个新旧String类型数组 * @author: HYJ * @create: 2019-11-08 11:13 */ public class CompareStringArrayUtil { /** * @param oldArr 旧数组 * @param newArr 新数组 * @return Map 包含两个数组,相较于旧数组,新数组多了哪些元素,以及少了哪些元素 */ public static Map<String, String[]> CompareStringArray(String[] oldArr, String[] newArr) { List<String> addList = new ArrayList<>(); List<String> deleteList = new ArrayList<>(); for (String anOldArr : oldArr) { if (!ArrayUtils.contains(newArr, anOldArr)) { deleteList.add(anOldArr); } } for (String aNewArr : newArr) { if (!ArrayUtils.contains(oldArr, aNewArr)) { addList.add(aNewArr); } } String[] addArr = addList.toArray(new String[addList.size()]); String[] deleteArr = deleteList.toArray(new String[deleteList.size()]); Map<String, String[]> res = new HashMap<>(); res.put("addArr", addArr); res.put("deleteArr", deleteArr); return res; } }
2、执行调用方法
public static void main(String[] args) { String[] oldArr = {"1","2"}; String[] newArr = {"1","3","4"}; Map<String, String[]> res = CompareStringArrayUtil.CompareStringArray(oldArr, newArr); System.out.println("deleteArr: "+ Arrays.toString(res.get("deleteArr"))); System.out.println("addArr: "+ Arrays.toString(res.get("addArr"))); }
3、运行结果
deleteArr: [2]
addArr: [3, 4]
本文转载链接:https://blog.csdn.net/Mr_EvanChen/article/details/80669079