Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #33975

Re: Stream question

From Sebastian <news@seyweiler.dyndns.org>
Newsgroups comp.lang.java.programmer
Subject Re: Stream question
Date 2016-03-15 21:21 +0100
Organization albasani.net
Message-ID <nc9qt2$h0t$1@news.albasani.net> (permalink)
References <nc9j3k$orv$1@dont-email.me>

Show all headers | View raw


Am 15.03.2016 19:11, schrieb Rhino:
[example snipped]
>
> How do I adjust what I have to get the number of orders for each agency
> code?
>

Two possibilities come to my mind.

(A) This answers your question of how to adjust what you have.

On Feb 22nd I posted in this group in the thread "stream filter twice", 
see 
https://groups.google.com/d/msg/comp.lang.java.programmer/zSqNcCNDCRI/mmeBA3w0DQAJ

In that post I discuss the possibility of using a so-called "combining 
collector" from the library jool (https://github.com/jOOQ/jOOL). In your 
case, such a collector would apply two downstream collectors 
simultaneously and return a pair of results:

// untested
Map<String, Tuple2<Integer, Long>> salesByAgency
            = ticketOrders.stream()
                .collect(groupingBy(TicketSale::getAgencyCode,
                         Tuple.collectors(
                            summingInt(TicketSale::getTicketsSold),
                            counting())));

If you don't want the dependency on the library, it is easy to write the 
collector yourself, see the post cited.

Notes:
1. Questions like this involving processing data from the same stream 
source multiple times in different ways come up very often. Jool 
provides a very neat way to deal with this need. Excellent library.

2. Besides summing, you can also do any other reduction using 
Collectors.reducing() as one of the downstream collectors.


(B) This does not adjust what you have, but is a different (and much 
simpler) way to do it.

Map<String, IntSummaryStatistics> salesByAgency
     = ticketOrders.stream()
         .collect(groupingBy(TicketSale::getAgencyCode,
                 Collectors.summarizingInt(TicketSale::getTicketsSold)));

IntSummaryStatistics has methods getCount() and getSum().

-- Sebastian




Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Stream question Rhino <no_offline_contact@example.com> - 2016-03-15 14:11 -0400
  Re: Stream question Sebastian <news@seyweiler.dyndns.org> - 2016-03-15 21:21 +0100
    Re: Stream question Rhino <no_offline_contact@example.com> - 2016-03-16 00:44 -0400

csiph-web