需求: 两个相同对象的list,需要将两个list的公共数据从第一个list中去掉。 /** * 将两个list中公共的数据从source list中去掉; * * @param source list1 * @param destination list2 * @return list1 - (list1 ∩ list2); */ public List<T> removeAll(List<T> source, List<T> destination) { List<T> result = new LinkedList<T>(); Set<T> destinationSet = new HashSet<>(destination); for (T t : source) { if (!destinationSet.contains(t)) { result.add(t); } } return result; } /** * 将两个list中filed字段相同的数据从source list中去掉 * * @param source list1 * @param destination list2 * @param field * @return */ public List<T> removeAll(List<T> source, List<T> destination, E field) { List<T> result = new LinkedList<>(); Map<E, T> destinationMap = new HashMap<E, T>(); Method m =null; try { for (T t : destination) { m = t.getClass().getMethod("get"+getMethodName((String)field)); destinationMap.put((E)m.invoke(t), t); } for (T t : source) { if (!destinationMap.containsKey((E)m.invoke(t))) { result.add(t); } } } catch (Exception e) { e.printStackTrace(); } return result; } /** * 获取方法名称 * @param field * @return * @throws Exception */ private String getMethodName(String field) throws Exception{ byte[] items = field.getBytes(); items[0] = (byte)((char)items[0] - 'a' + 'A'); return new String(items); }
List高效remove方法,自定义比较字段后remove
最新推荐文章于 2024-01-12 23:06:33 发布