Best way to sum an integer list [duplicate] - java

This question already has answers here:
Is there possibility of sum of ArrayList without looping
(13 answers)
Closed 6 years ago.
I was wondering what the best way to sum the elements of an integer list in java is.
I'm aware I could perform this with a for loop but I was expecting there might be inbuilt ways to do this, such as the reduce function in other languages.
The relevant code for this problem has been provided below.
public static int sumList(List<Integer> list) {
return 0; //should return sum of integers in list
}

You can use the Stream API in Java 8
return list.stream().mapToInt(i -> i).sum();
The .mapToInt(i -> i) is required as Java doesn't know how to sum any object but it does know how to sum an IntStream and this converts the Stream<Integer> into an IntStream

Related

Print out int[][] array using streams [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I have a method rotateImage that returns an int[][] array, I am having trouble understaing how to display the actual values of the array instead of just the hashcode:
[I#548c4f57
[I#1218025c
[I#816f27d
I tried doing this:
Arrays.stream(rotateImage(matrix)).forEach(System.out::println);
but that only returns the hashcode, not the actual numbers themselves. I also tried using to Arrays.toString() method in several ways but always get an error.
It's cause you're accessing the address and not the actual values. You can simply do a lambda function and iterate through each row
Arrays.stream(rotateImage(matrix)).
forEach(row -> {
for(int i : row) {
System.out.println(i);
}
});

Sum a list of objects based on BigDecimal field in single line [duplicate]

This question already has answers here:
Adding up BigDecimals using Streams
(5 answers)
Closed 3 years ago.
Suppose we have:
class Foo {
public BigDecimal field;
}
and that we have a list of Foo instances, i.e. List<Foo> list.
How can we calculate the sum of the values of the field from the objects in the list in a single line?
I found examples of similar cases using streams but they handle simpler cases and do not work for this; such as calculating for List<Integer> or when the field is something easily "summable" (int, Integer...).
list.stream().map(foo -> foo.field).reduce(BigDecimal.ZERO, (a, b) -> a.add(b));

Take every nth. element out of an Array of Objects using streams [duplicate]

This question already has answers here:
Is there a concise way to iterate over a stream with indices in Java 8?
(24 answers)
Closed 3 years ago.
I am trying to solve little easy exercises with streams and I was wondering which way is the most efficient way to get a stream out of an Person[] but taking every second object.
Person[] myarr = {person1, person2, person3, person4, person5};
The output stream should consist of the objects person1, person3, person5 Any good efficient ideas?
IntStream.range(0, myarr.length)
.filter(i -> i % 2 == 0)
.mapToObj(i -> myarr[i]);

Merge each element of multiple lists into one Element and return another list in java 8 [duplicate]

This question already has answers here:
Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)
(14 answers)
Closed 5 years ago.
for simplicity I have 2 lists of String and I need to join the strings into one and create another list.
For eg --
List 1 = [a,b,c,d]
List 2 = [e,f,g,h]
I want the output as
List3 = [ae,bf,cg,dh]
I can do this using regular for loops. but dont know how to proceed for java8
I am trying to get myself thinking in n Java 8 :-)
I'm not sure there's a better (easy) way to do this than to access the elements from the two lists by index:
List<String> zipped = IntStream.range(0, list.size())
.mapToObj(i -> list1.get(i) + list2.get(i))
.collect(Collectors.toList());

Converting String of digits to List of integer [duplicate]

This question already has answers here:
How do I convert a Java 8 IntStream to a List?
(5 answers)
Closed 7 years ago.
I am doing some hands on exercise on java 8 stream features so thought of applying the knowledge with the problem Converting String of digits to List of integer
a typical test would look like
#Test
public void testGetListofIntegersFromString(){
List<Integer> result = getIntegers("123456780");
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,0),result);
}
I have written below method
List<Integer> getIntegers(String value) {
return IntStream.rangeClosed(0, value.length() - 1).map(i -> Integer.valueOf(value.substring(i,i+1))).collect(?????);
}
I am stuck about which function to use to get The List Of Integers
I tried collect(Collectors.toList()) Its giving compilation error.
Please suggest if we can follow different to solve this .
Use String.chars():
"123456780".chars().map(c -> c-'0').boxed().collect(Collectors.toList());

Categories