Calculate average in java

后端 未结 10 2148
悲哀的现实
悲哀的现实 2020-12-11 07:49

EDIT: Ive written code for the average, but i dont know how to make it so that it also uses ints from my args.length rather than the array

I need to

10条回答
  •  青春惊慌失措
    2020-12-11 08:17

    It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.

    • In your case, you want to convert args which is String[] into double or int. You can do this using Arrays.stream(). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
    • Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
    • If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.

提交回复
热议问题