collect(Collectors.summingInt(Integer::intValue)) items. reduce(0, (a, b) -> a + b) Integer sum = items.stream() Now, that's a bit difficult to find by hand, and we can use the crunching power of loops to do this calculation for us easily. A good problem to solve using Java code is to find the list of all numbers which are Prime till, let's say 100. reduce(0, Integer::sum) Integer sum = items.stream() You would implement an algorithm that finds prime numbers using the java programming language Perhaps the sieve of eratosthenes will help you: Sieve of. A Prime number is a Number whose only factors are 1 and the Number itself. Implementing this observation in an efficient manner would certainly not make the code concise, but would dramatically speed it up. In this case, in order to calculate the sum using the methods shown in previous examples, we need to call the map() method to convert our stream into a stream of integers.Īs a result, we can use Stream.reduce(), llect(), and IntStream.sum() to calculate the sum: Integer sum = items.stream() A reversible prime cannot start with a 2, 4, 5, 6, or 8, because when reversed, the number will be divisible by two or five, and thus won't be prime. List items = Arrays.asList(item1, item2, item3, item4) Next let's imagine that we want to calculate the total price of all the items of the following list: Item item1 = new Item(1, 10) Let's imagine that we have a list of objects and that we want to calculate the sum of all the values of a given field of these objects.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |