16

I am studying java Stream and having hard time solving questions below. The reason why I got stuck is because I have no idea about dealing with Stream<Integer>.

I stumbled upon a solution of "count" by doing list.stream().count(), but other than this, I can't proceed further. Please help me how to deal with these problems and tell me why list.stream().count() works in this situation. So far, I've tried everything I've learned.

public class Question {
    public static void main(String[] args) {
        List<Integer>list = Arrays.asList(5,3,4,1,2);
        System.out.println("sum by using Stream : " + sum);
        System.out.println("count by using Stream: " + count);
        System.out.println("average by using Stream : " + avg);
        System.out.println("sort by using Stream");
    }
}
banan3'14
  • 3,810
  • 3
  • 24
  • 47
KingJinho
  • 683
  • 1
  • 6
  • 23
  • Is it me or is your code here incomplete ? How is `sum`, `count` and `avg` being initialized? – KarelG Feb 21 '18 at 12:59
  • Did you have a look at the Streams API? It tells you what methods exist. And there are lots, lots of informations at the Oracle site. – glglgl Feb 21 '18 at 13:00
  • 2
    Also [`.count()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#count--) from a streamable gives you the _number_ of elements in that stream. – KarelG Feb 21 '18 at 13:00
  • it is incomplete, so i need lines of code to work out those system.out.println() and i don`t know how to get the sum, avg, and sort. – KingJinho Feb 21 '18 at 13:01
  • 3
    Start here: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html the example even shows sample code of a sum. – AlexC Feb 21 '18 at 13:04
  • If one of the answers solved the problem, can you [accept one of them](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) as the correct solution? (and upvote on the useful ones) – Juan Carlos Mendoza Mar 14 '18 at 20:23

4 Answers4

35
IntSummaryStatistics stats = Arrays.asList(1,2,3,4)
    .stream()
    .mapToInt(Integer::intValue)
    .summaryStatistics();

stats.getSum();
stats.getCount();
stats.getAverage();

For the sorted, you will have to stream again.

banan3'14
  • 3,810
  • 3
  • 24
  • 47
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 5
    or `Arrays.asList(1,2,3,4) .stream() .collect(Collectors.summarizingInt(Integer::intValue));` – Holger Feb 21 '18 at 13:29
  • @Holger Is there a way to know when to choose one implementation or the other? I mean, many times, there are operations that can be done either with stream intermediate operations or with collectors, i.e. `Stream.map` vs `Collectors.mapping`, reducing, fitlering, flatmapping and summarizing, etc – fps Feb 21 '18 at 16:00
  • 3
    @FedericoPeraltaSchaffner for this specific case, it doesn’t matter and the choice is yours. It’s worth knowing both, as it may make a difference when you want to extend the code, see [this answer](https://stackoverflow.com/a/37025002/2711488) for details. And [this one](https://stackoverflow.com/a/44259061/2711488). – Holger Feb 21 '18 at 17:28
  • @Eugene The IntSummaryStatistics idea was a recent memory finally :) – davidxxx Feb 25 '18 at 21:42
12

The reason of why list.stream().count() works but list.stream().sum() doesn't is because list.stream() returns a Stream<Integer> and there is a Stream::count method, but there isn't a Stream::sum or Stream::average.

To get the sum and avg first you have to map each integer value in the Stream<Integer> that you get when you do list.stream() to an IntStream. This is the int primitive specialization of Stream. This can be done using the Stream::mapToInt method:

list.stream().mapToInt(Integer::intValue)

Doing this you can use the methods IntStream::sum and IntStream::average:

System.out.println("sum by using Stream : " + list.stream().mapToInt(Integer::intValue).sum());
System.out.println("average by using Stream : " + list.stream().mapToInt(Integer::intValue).average());

Or even better, you can use the IntStream::summaryStatistics to get the sum, count and avg together (also the min and the max value):

System.out.println("sum, count, avg, min and max using Stream : " + list.stream().mapToInt(Integer::intValue).summaryStatistics());

To sort the values you can use the Stream::sorted method:

System.out.println("sort by using Stream: " + list.stream().sorted().collect(Collectors.toList()));

Here is a good post that can help you to understand how to use the Java 8 Stream Api.

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
4

You can do just like this:

List<Integer> list = Arrays.asList(5,3,4,1,2);
        System.out.println("sum by using Stream : " + list.stream().mapToInt(Integer::intValue).sum());
        System.out .println("count by using Stream: " + list.stream().mapToInt(Integer::intValue).count());
        System.out.println("average by using Stream : " + list.stream().mapToInt(Integer::intValue).average());
        System.out.println("sort by using Stream: " + list.stream().sorted().collect(Collectors.toList()));
Yaroslav
  • 446
  • 4
  • 15
3

You should use mapToInt or mapToDouble

and you can print list by forEach(System.out::println)

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

System.out.println("sum by using Stream : " + list.stream().mapToInt(Integer::intValue).sum());

System.out .println("count by using Stream: " + list.stream().count());

System.out.println("average by using Stream : " + list.stream().mapToInt(Integer::intValue).average());

System.out.println("sort by using Stream: " );

list.stream().sorted().forEach(System.out::println);
Azzabi Haythem
  • 2,318
  • 7
  • 26
  • 32