How to convert List to Set (ArrayList to HashSet)
List<TestObject> list1 = new ArrayList<TestObject>();
List<String> list2 = new ArrayList<>();
List<String> filtedlist = new ArrayList<>();
TestObject to = new TestObject();
to.setCode("a1");
list1.add(to);
to = new TestObject();
to.setCode("a2");
list1.add(to);
to = new TestObject();
to.setCode("a3");
list1.add(to);
to = new TestObject();
to.setCode("a4");
list1.add(to);
to = new TestObject();
to.setCode("a5");
list1.add(to);
list2.add("a2");
list2.add("a4");
list2.add("a2");
list2.add("a4");
list2.add("a2");
list2.add("a4");
//寫法一
for (TestObject testo : list1) {
if(list2.contains(testo.getCode())) {
filtedlist.add(testo.getCode());
}
}
//寫法二
Set<String> set = new HashSet<String>(list2);//Convert List to Set
for (TestObject testo : list1) {
if(set.contains(testo.getCode())) {
filtedlist.add(testo.getCode());
}
}
for (TestObject testo : list1) {
System.out.println("all==>"+testo.getCode());
}
for (String string : list2) {
System.out.println("override==>"+string);
}
for (String string : filtedlist) {
System.out.println("filted==>"+string);
}