Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- }
Add Comment
Please, Sign In to add comment