Skip to content
Advertisement

Create list of objects from another list by using java8 stream

I have a list student list A and I have student list B.

Student objects contains some fields like that : no,age,city,birth_date,salary

My list A contains these objects

A=[1 , 20 , Rome ,    2001, 300 ]
  [2 , 21 , Dublin ,  2005, 250 ]
  [3 , 24 , Istanbul, 2012, 350 ]
  [4 , 27 , Madrid ,  2002, 450 ]
  [5 , 27 , London ,  2005, 650 ]

My list B contains these objects

B=[1,  20 , Rome ,    2014, 700 ]
  [3,  24 , Istanbul, 2012, 350 ]
  [4,  27 , Madrid,   2009, 450 ]

What i want to do is extract student objects that ListA have but listB not and ListA and ListB have(as no,age,city) but salary is different.Also I want to write salary diff.

 Result set = [5 , 27 ,London, 2005, 650 ]
              [2 , 21 ,Dublin ,2005, 250 ]
              [1,  20, Rome ,  2001, -400]

I want to use stream api in java 8.First of all , I want to extract students objects to a list but I can extract common student objects now.I tried tu use noneMatch but it is not working.Do you have any idea?

List<Student> listDiffList = A.stream()
            // We select any elements such that in the stream of elements from the second list
            .filter(two -> B.stream()
            // there is an element that has the same name and school as this element,
                .anyMatch(one -> one.getNo().equals(two.getNo()) 
                        && one.getAge().equals(two.getAge())
                        && one.getCity().equals(two.getCity())))
            // and collect all matching elements from the first list into a new list.
            .collect(Collectors.toList());

Advertisement

Answer

I used custom Collector object, looks not very nice but it seems working:

List<Student> listDiffList =
  A.stream()
   .collect(ArrayList::new,
           (a, two) -> {
             Optional<Student> one = B.stream()
                                      .filter(s -> s.getNo().equals(two.getNo())
                                                   && s.getAge().equals(two.getAge())
                                                   && s.getCity().equals(two.getCity()))
                                      .findAny();


             if (one.isPresent()) {
                 if (!one.get().getSalary().equals(two.getSalary())) {
                     two.setSalary(two.getSalary()-one.get().getSalary());
                     a.add(two);
                 }
             }
             else a.add(two);
           },
           ArrayList::addAll);
Advertisement