Java——List合并
按照pid、id合并两个集合
package cn.swsk.xbry.mess.controller;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* List合并
* @author css
* @data 2019/7/11 15:28
*/
public class JoinList<T> {
private List<T> p;
private List<?> c;
private Field pf;
private Field plf;
private Field cf;
private Field getField(Class<?> clazz, String name) {
try {
Field f = clazz.getDeclaredField(name);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
public void setParent(List<T> p, String name, String children) {
this.p = p;
Class<?> clazz = p.get(0).getClass();
this.pf = getField(clazz, name);
this.plf = getField(clazz, children);
}
public void setChild(List<?> c, String name) {
this.c = c;
Class<?> clazz = c.get(0).getClass();
this.cf = getField(clazz, name);
}
public List<?> join() throws IllegalAccessException, InstantiationException {
for (T t: p) {
Object pv = pf.get(t);
for (Object o: c) {
Object cv = cf.get(o);
if(pv.equals(cv)){
Collection list = (Collection<?>) plf.get(t);
if(list == null){
list = new ArrayList();
list.add(o);
plf.set(t, list);
} else {
list.add(o);
}
}
}
}
return this.p;
}
static class A{Integer id; String name;List<B> list;
@Override
public String toString() {
return "A{" +
"id=" + id +
", name='" + name + '\'' +
", list=" + list +
'}';
}
}
static class B{Integer pid; String name;
@Override
public String toString() {
return "B{" +
"pid=" + pid +
", name='" + name + '\'' +
'}';
}
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
A a = new A();
a.id = 3;
a.name = "a";
B b = new B();
b.pid = 3 ;
b.name = "b";
List<A> al = new ArrayList<>();
List<B> bl = new ArrayList<>();
al.add(a);
bl.add(b);
JoinList<A> test = new JoinList<>();
test.setParent(al, "id", "list");
test.setChild(bl, "pid");
System.out.println(test.join());
}
}
以上是 Java——List合并 的全部内容, 来源链接: utcz.com/z/389784.html