BAEL-1586 Sum and Average in Java Array (#3718)

* Evaluation Article

* CR comments resolved

* BAEL-1586 Find Sum and Average in Java Array

* Revert "CR comments resolved"

This reverts commit c9bf88fcd5.

* Revert "Evaluation Article"

This reverts commit 41ad30313a.

* BAEL-1586 Removed Author Description

* BAEL-1586 Find Sum And Avergae In Array

* remove excess whitespace
This commit is contained in:
raghav-jha
2018-03-07 21:29:50 +05:30
committed by pauljervis
parent 52d257a545
commit 4526bb6add
6 changed files with 161 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
package com.baeldung.array;
public class Find2ndLargestInArray {
public static int find2ndLargestElement(int[] array) {
int maxElement = array[0];
int secondLargestElement = -1;
for (int index = 0; index < array.length; index++) {
if (maxElement <= array[index]) {
secondLargestElement = maxElement;
maxElement = array[index];
} else if (secondLargestElement < array[index]) {
secondLargestElement = array[index];
}
}
return secondLargestElement;
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.array;
import java.util.Arrays;
public class FindElementInArray {
public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
boolean actualResult = false;
for (int index = 0; index < array.length; index++) {
if (element == array[index]) {
actualResult = true;
break;
}
}
return actualResult;
}
public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.array;
import java.util.Arrays;
public class SumAndAverageInArray {
public static int findSumWithoutUsingStream(int[] array) {
int sum = 0;
for (int index = 0; index < array.length; index++) {
sum += array[index];
}
return sum;
}
public static int findSumUsingStream(int[] array) {
return Arrays.stream(array).sum();
}
public static double findAverageWithoutUsingStream(int[] array) {
int sum = findSumWithoutUsingStream(array);
return (double) sum / array.length;
}
public static double findAverageUsingStream(int[] array) {
return Arrays.stream(array).average().getAsDouble();
}
}