我有两个列表,其中包含一些对象(Fruit类)。我正在使用第三个列表根据以下两个条件添加这些元素。
我希望将第一个列表中的每个对象都添加到第三个列表中。但是,如果在第二个列表中有匹配的对象(基于id和isChecked进行匹配),则我希望将来自第二个列表的对象添加到第三个列表中并忽略第一个列表中的对象。
如果我执行了第一点提到的切换操作,则我希望将该对象移动到第三个列表的第一个元素处。
我已经用下面的代码使其正常工作。但是,我觉得它非常低效。是否有更好的解决方法?
请注意,我无法控制第二个列表,但第一个列表来自Rest端点,我当前将其捕获为列表。不确定是否应该选择Map,请给出建议。
示例:
在下面的示例中,期望的列表输出为[f2,f5,f1,f3,f4](基于名称)。
这是因为我拥有来自第一个列表的所有元素。 f2和f5在顺序前面,因为它们来自第二个列表(它们匹配了第一个列表中的元素并且isChecked设置为true)。
我希望将第一个列表中的每个对象都添加到第三个列表中。但是,如果在第二个列表中有匹配的对象(基于id和isChecked进行匹配),则我希望将来自第二个列表的对象添加到第三个列表中并忽略第一个列表中的对象。
如果我执行了第一点提到的切换操作,则我希望将该对象移动到第三个列表的第一个元素处。
我已经用下面的代码使其正常工作。但是,我觉得它非常低效。是否有更好的解决方法?
请注意,我无法控制第二个列表,但第一个列表来自Rest端点,我当前将其捕获为列表。不确定是否应该选择Map,请给出建议。
示例:
在下面的示例中,期望的列表输出为[f2,f5,f1,f3,f4](基于名称)。
这是因为我拥有来自第一个列表的所有元素。 f2和f5在顺序前面,因为它们来自第二个列表(它们匹配了第一个列表中的元素并且isChecked设置为true)。
import lombok.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class App {
public static void main(String[] args) {
Fruit fruit1 = new Fruit("1", "f1", false);
Fruit fruit2 = new Fruit("2", "f2", false);
Fruit fruit3 = new Fruit("3", "f3", false);
Fruit fruit4 = new Fruit("4", "f4", false);
Fruit fruit5 = new Fruit("5", "f5", false);
List<Fruit> firstList = Arrays.asList(fruit1, fruit2, fruit3, fruit4, fruit5);
Fruit fruit6 = new Fruit("2", "f2", true);
Fruit fruit7 = new Fruit("7", "f7", false);
Fruit fruit8 = new Fruit("5", "f5", true);
Fruit fruit9 = new Fruit("9", "f9", false);
Fruit fruit10 = new Fruit("10", "f10", false);
List<Fruit> secondList = Arrays.asList(fruit6, fruit7, fruit8, fruit9, fruit10);
List<Fruit> finalList = new ArrayList<>();
// expected list = [f2, f5, f1, f3, f4]
// this loop is checking and adding objects to finalList.
// must match the first list and isChecked.
// in this case, only f6 and f8 matches the first list (id match) and is also 'checked'.
for (Fruit first : firstList){
for (Fruit second : secondList){
if(first.getId().equals(second.getId()) && second.isChecked()){
finalList.add(second);
break;
}
}
}
// not done yet. Still need to loop and add back the elements from the first list
// which were not added in the above loop
boolean addedFirst = false;
outer:
for(Fruit first : firstList){
for(Fruit finalFruit : finalList){
if(first.getId().equals(finalFruit.getId())){
continue outer;
}
}
finalList.add(first);
}
for(Fruit fruit : finalList){
System.out.println(fruit);
}
}
}
@Getter
@Setter
@ToString
class Fruit{
private String id;
private String name;
private boolean isChecked;
Fruit(String id, String name, boolean isChecked) {
this.id = id;
this.name = name;
this.isChecked = isChecked;
}
}