Lycone
Lycone

Reputation: 650

Java-Stream-API: Map Reduce

Let say I've got multiple java objects from type obj_vx with each differents date time(as member variable).

obj_v1[D1]
obj_v1[D2]
obj_v1[D3]
obj_v1[D4]

obj_v2[D2]
obj_v2[D3]
obj_v2[D4]

obj_v3[D2]
obj_v3[D3]
obj_v3[D4]

obj_v4[D1]
obj_v4[D2]
obj_v4[D5]


obj_v5[D1]
obj_v5[D4]
obj_v5[D5]
obj_v5[D6]

obj_v5[D4]
obj_v5[D5]

or 

obj_v1 [D1, D2, D3, D4]
obj_v2 [D2, D3, D4]
obj_v3 [D2, D3, D4]
obj_v4 [D1, D2, D5]
obj_v5 [D1, D4, D5, D6]
obj_v6 [D4, D5]

Now, I want to filter for a given date D (with D1 < D < D6) the obj_vx with the youngest date time (D2 is younger than D1) which is still older(or equals) than D. Can anyone tells me, how to build it with the Java-Stream-API?

The Map-Reduce operation returns a list of obj_vx objects.

Response:

- after 1st iteration
obj_v1 [D1, D2, D3]
obj_v2 [D2, D3]
obj_v3 [D2, D3]
obj_v4 [D1, D2]
obj_v5 [D1]
- after 2nd iteration
obj_v1[D3], obj_v2[D3], obj_v3[D3], obj_v4[D2], obj_v5[D1].

Proposition:

public class FilterTest {
       static class X {
             String group;
             int y;

             X(String group, int y) {
                    this.group = group;
                    this.y = y;
             }

             public String getGroup() {
                    return group;
             }

             public int getY() {
                    return y;
             }

             @Override
             public String toString() {
                    return String.format("[group: '%s', y: '%s']", group, y);
             }
       }

       public static void main(String[] args) {
             int val = 2;

             List<X> l = new ArrayList<>();
             l.add(new X("A", 1));
             l.add(new X("Y", 3));
             l.add(new X("A", 2));
             l.add(new X("Y", 1));
             l.add(new X("B", 8));
             l.add(new X("A", 3));

             Map<String, X> map = l.stream().filter(d -> d.y <= val).collect(
                     Collectors.groupingBy(X::getGroup,
                         Collectors.collectingAndThen(
                             Collectors.reducing(
                                        (X d1, X d2) -> d1.getY() > d2.getY() ? d1 : d2
                           ),
                             Optional::get)));
             System.out.println("m: " + map);     
       }
}

Upvotes: 2

Views: 161

Answers (1)

Naman
Naman

Reputation: 31878

A better way to represent your proposition could be :

Map<String, X> map = l.stream()
        .filter(d -> d.getY() <= val)
        .collect(Collectors.toMap(X::getGroup, Function.identity(), 
                BinaryOperator.maxBy(Comparator.comparing(X::getY))));

Upvotes: 1

Related Questions