Guest User

Untitled

a guest
Jan 17th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. import lombok.*;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6.  
  7. public class App {
  8. public static void main(String[] args) {
  9.  
  10. Fruit fruit1 = new Fruit("1", "f1", false);
  11. Fruit fruit2 = new Fruit("2", "f2", false);
  12. Fruit fruit3 = new Fruit("3", "f3", false);
  13. Fruit fruit4 = new Fruit("4", "f4", false);
  14. Fruit fruit5 = new Fruit("5", "f5", false);
  15.  
  16. List<Fruit> firstList = Arrays.asList(fruit1, fruit2, fruit3, fruit4, fruit5);
  17.  
  18. Fruit fruit6 = new Fruit("2", "f2", true);
  19. Fruit fruit7 = new Fruit("7", "f7", false);
  20. Fruit fruit8 = new Fruit("5", "f5", true);
  21. Fruit fruit9 = new Fruit("9", "f9", false);
  22. Fruit fruit10 = new Fruit("10", "f10", false);
  23.  
  24. List<Fruit> secondList = Arrays.asList(fruit6, fruit7, fruit8, fruit9, fruit10);
  25.  
  26. List<Fruit> finalList = new ArrayList<>();
  27.  
  28. // expected list = [f2, f5, f1, f3, f4]
  29.  
  30. // this loop is checking and adding objects to finalList.
  31. // must match the first list and isChecked.
  32. // in this case, only f6 and f8 matches the first list (id match) and is also 'checked'.
  33. for (Fruit first : firstList){
  34. for (Fruit second : secondList){
  35. if(first.getId().equals(second.getId()) && second.isChecked()){
  36. finalList.add(second);
  37. break;
  38. }
  39. }
  40. }
  41.  
  42. // not done yet. Still need to loop and add back the elements from the first list
  43. // which were not added in the above loop
  44. boolean addedFirst = false;
  45. outer:
  46. for(Fruit first : firstList){
  47. for(Fruit finalFruit : finalList){
  48. if(first.getId().equals(finalFruit.getId())){
  49. continue outer;
  50. }
  51. }
  52. finalList.add(first);
  53. }
  54.  
  55. for(Fruit fruit : finalList){
  56. System.out.println(fruit);
  57. }
  58. }
  59. }
  60.  
  61. @Getter
  62. @Setter
  63. @ToString
  64. class Fruit{
  65. private String id;
  66. private String name;
  67. private boolean isChecked;
  68.  
  69. Fruit(String id, String name, boolean isChecked) {
  70. this.id = id;
  71. this.name = name;
  72. this.isChecked = isChecked;
  73. }
  74. }
Add Comment
Please, Sign In to add comment