1

I have 2 List entities, I don't want to compare it by nested loop if it possible,

let say I have entities like this :

List<Entity1> = entity1Repository.findByCode(String code);
List<Entity2> = entity2Repository.findByName(String name);

and I want to compare those entities, I want the result of the list which that List only value which has the same value,

such as this= [1, 2, 4] and [1,2,5] and i want the result like this ==> [1,2]

how to do that in Java?

poppop
  • 137
  • 13
  • If Entity1 and Entity2 have no common supertype (Emtkty Interface) you can use Object in the below answers and must write a static helper function which extracts and compares the values `static boolean isSameEntityValue(Entity1 es, Entity2 e2)` – eckes Jul 04 '19 at 07:51

3 Answers3

1

You can write a function that returns a list containing intersecting elements of 2 list passed as paramters:

public <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }
jarvo69
  • 7,908
  • 2
  • 18
  • 28
1

Assuming input:

List<Integer> l1 = Arrays.asList(1, 2, 3, 4);
List<Integer> l2 = Arrays.asList(11, 2, 5, 4);

Listing two ways:

    //method 1
    List<Integer> result = l1.stream().filter(l2::contains).collect(Collectors.toList());
    System.out.println(result);

    //method 2
    Set<Integer> s1 = new HashSet<>(l1);
    s1.retainAll(l2);

    System.out.println(s1);
    System.out.println(l1);

In method1: you are using streams, a wonderful concept from java

In method2: you are creating another set, and calling retainAll() on it. This will remove other elements from s1, but no affect on original list l1.

Gorav Singal
  • 508
  • 3
  • 11
  • will it work also in List and List ? because your example is List, i am stil very new about Java – poppop Jul 04 '19 at 07:38
  • Your class: "Entity" must have at least the method: @Override public boolean equals(Object obj) {...} – Gorav Singal Jul 04 '19 at 07:41
  • can u give example how to write this on the entity ? i have tried it but still don't understand and now rok – poppop Jul 04 '19 at 07:42
0

You can use Java 8 Stream api to get common elements from two lists.

List<Entity> commonEntity = entity1.stream() .filter(entity2::contains) .collect(Collectors .toList()));