简体   繁体   中英

Java Streams with combining multiple rows to one

My code consists of a class with 10 variables. The class will get the data from a database table and the results from it is a List. Here is a sample class:

@Data
class pMap {
    long id;
    String rating;
    String movieName;
}

The data will be as follows:

id=1, rating=PG-13, movieName=
id=1, rating=, movieName=Avatar
id=2, rating=, movieName=Avatar 2
id=2, rating=PG, movieName=

I want to combine both the rows to a single row grouping by id using Java streams. The end result should like this Map<Long, pMap> :

1={id=1, rating=PG-13, movieName=Avatar},
2={id=2, rating=PG, movieName=Avatar 2}

I am not sure how I can get the rows combined to one by pivoting them.

You can use toMap to achieve this:

Map<Long, pMap> myMap = myList.stream().collect(Collectors.toMap(x -> x.id, Function.identity(),
                (x1, x2) -> new pMap(x1.id, x1.rating != null ? x1.rating : x2.rating, x1.movieName != null ? x1.movieName : x2.movieName)));

I am passing two functions to toMap method:

  1. First one is a key mapper. It maps an element to a key of the map. In this case, I want the key to be the id.
  2. The second one is a value mapper. I want the value to be the actual pMap so this is why I am passing the identity function.
  3. The third argument is a merger function that tells how to merge two values with the same id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM