I have gone through a few web resources and links, however, I am unable to find the sum of elements of an Integer ArrayList without looping. I am looking for a function which will allow me to do this in a single line.
I was able to find the same for a normal array as follows
import java.util.ArrayList;
import java.util.stream.IntStream;
public class sumArray
{
public static void main(String[] args)
{
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
}
}
I can write a user-defined function as follows
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(sum(al));
}
static int sum(ArrayList<Integer> al)
{
int value = 0;
for(int i : al)
{
value += i;
}
return value;
}
}
However, I'm looking for something in-built.
Please advise.
EDIT : I have tried the following but I get build errors
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
System.out.println(getVersion());
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(al.stream().mapToInt(Integer::intValue).sum());
}
static double getVersion () {
String version = System.getProperty("java.version");
int pos = version.indexOf('.');
pos = version.indexOf('.', pos+1);
return Double.parseDouble (version.substring (0, pos));
}
}
Errors
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Integer cannot be resolved to a variable
Syntax error on tokens, delete these tokens
You can easily map a Stream<Integer> to an IntStream and then calculate the sum :
a1.stream().mapToInt(Integer::intValue).sum();
al.stream().reduce(0, (x,y) -> x+y)
Related
My setAverage method is getting a list of numbers to sum them up. If I give an ArrayList of lets say 200 200 200, the outcome is 600. But if I give it 200 200 250, the coutome is the same. I do not get it.
Also: I do not want to get the average now, I am at the point of just sum up the array.
import java.util.ArrayList;
public class calculation {
private ArrayList<Integer> x;
private int z;
public void setAverage(ArrayList<Integer> myList) {
x = myList;
for(int i: myList) {
z += i;
break;
}
}
public int getAverage() {
return z;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class eingaben {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation rechneAVG = new calculation();
ArrayList<Integer> myList = new ArrayList<Integer>();
while(scan.hasNextInt()) {
myList.add(scan.nextInt());
rechneAVG.setAverage(myList);
}
System.out.println(rechneAVG.getAverage());
}
}
Typically you're not looking to use a break statement in a foreach style loop, the break will terminate the loop which is what is causing your issues here.
Also I'm not a big fan of what you're doing with the setting of x to the value of the input list. Could you maybe restructure the function to return a value that is added to your list? Not really part of your question, more of an aside.
Assuming you are doing something like this before
ArrayList<Integer> list = Arrays.asList(new int[] {200,200,250});
calculation calc = new calculation();
calc.setAverage(list);
Then you should rewrite your class like this:
import java.util.ArrayList;
public class Calculation {
private ArrayList<Integer> intList;
private int avg;
public void setAverage(ArrayList<Integer> myList) {
intList = myList;
avg = 0;
for(int i: myList) {
avg += i;
}
}
public int getAverage() {
return avg;
}
}
That is: initialize z (I renamed it to avg) and ditch the break;
Also, never use break. I am fighting my own crusade to stop coders from using break/continue, but they tell me I'm crazy.
I'm new to Java coding, and I'm stuck with a simple ArrayList sum code. I believe that my method is correct, but I don't understand the main method. I tried to run it many times, but it keeps saying that my input, ArrayList ar, is not 'identified'. Help needed!
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the simpleArraySum function below.
*/
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = Integer.parseInt(scanner.nextLine().trim());
int[] ar = new int[arCount];
String[] arItems = scanner.nextLine().split(" ");
for (int arItr = 0; arItr < arCount; arItr++) {
int arItem = Integer.parseInt(arItems[arItr].trim());
ar[arItr] = arItem;
}
int result = simpleArraySum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
}
// Below is my code
public static int simpleArraySum(int n, ar) {
/** It says that 'ar' is not identified. I tried
'Arraylist<Integer>
* ar but it still won't work
int sum = 0;
for (int i = 0; i < ar.size(); i++) {
sum += ar.get(i);
}
return sum;
}
}
This is what it returns:
Compile Message:
Solution.java:39: error: <identifier> expected
public static int simpleArraySum(int n, ar) {
^
1 error
The declaration of type of parameters for the method simpleArraySum is missing.
Try the following signature, it should work
public static int simpleArraySum(int n,int[] ar) {
This is the code I'm trying to use in Bluej to return values higher than my target value:
import java.util.ArrayList;
public class BiggestValue
{
public ArrayList<Integer> getBiggerValues (int target, ArrayList<Integer> list)
{
ArrayList<Integer> result = new ArrayList<Integer> ();
for (int ix=0; ix < list.size(); ix++)
{
int currentItem = list.get(ix);
if (currentItem > target)
{
result.add (currentItem);
}
}
return result;
}
}
It compiles but when I put in values to get the result I get the following message:
can anyone help?
Thanks
Lydia
You could pass new ArrayList<Integer>(Arrays.asList(new Integer[]{14, 19, 20})) as the second parameter or you could write a main method as shown below:
public static void main(String args[]){
BiggestValue bV = new BiggestValue();
ArrayList bigs = bV.getBiggerValues(17, new ArrayList<Integer>(Arrays.asList(new Integer[]{14, 19, 20})));
//methods to display the output.
}
I need to split this code in a way where I would be calling it from the main and doing the sorting in another method in a different file.
This is what I have in the main:
public class Test {
public static void main(String[] args) {
//array of 10 numbers
double numbers[] = new double[]{1.9, 2.5, 3.7, 2, 1.5, 6, 3 , 4 , 5, 2};
//assign first element of an array to largest and smallest
double smallest = numbers[0];
double largetst = numbers[0];
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] < smallest)
smallest = numbers[i];
}
System.out.println("The minimum number is: " + smallest);
}
}
This is the other method:
import java.util.Arrays;
public class Chapter8 {
public static void chap8method(){}
public static double[][] sortRows(double[][] m) {
Chapter8.chap8method();
double[][] result = Chapter8.sortRows(m);
}
}
Create a class with the main method.
Main.java
public class Main {
public static void main(String[] args) {
//if your sort method is static in another class
Sort.sortRows(
//if your method is non static than create an object of that class
Sort obj = new Sort();
obj.sortRows
}
}
Your another class:
Sort.java
public class Sort{
public static double sortRows(double[][] m) {
//your sorting logic here
}
}
I'm working on a homework problem that is asking me to write a program that generates 20 random numbers (0-99) in an array and then sorts and prints them.
I am getting crazy errors in my methods and I can't figure out whats wrong. I keep getting errors "Illegal start of expression, ; expected and .class expected. Any advice would be great.
import java.util.Arrays;
public class P6_14
{
public static void main(String[] args)
{
System.out.println("This program will sort randomly generated numbers");
public static int[] createNumbers(int n)
{
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
numbers[i] = (int) (Math.random() * 99 + 1);
}
return numbers;
}
public static void orderArray(int[] array)
{
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}
}
The way your trying to fit everything into one main method isnt very OOP. Try to create methods in the future within your class! Hope this help
import java.util.Arrays;
public class Hello{
private int[] numbers = new int[20];
public Hello(){
for (int i = 0; i < this.numbers.length; i++)
{
this.numbers[i] = (int) Math.floor(Math.random()*99);
}
}
public void orderArray()
{
Arrays.sort(this.numbers);
}
public void printArray()
{
for (int i = 0; i < 20; i++)
{
System.out.println(this.numbers[i]);
}
}
public static void main(String[] args)
{
System.out.println("This program will sort randomly generated numbers1");
Hello test = new Hello();
System.out.println("Printing randomized");
test.printArray();
test.orderArray();
System.out.println("Printing sorted");
test.printArray();
}
}