Comment faire la somme des valeurs dans la liste en utilisant Java 8
5 réponses
vous voulez flatMap à un IntStream. Après cela, prendre la somme est facile.
int sum = counts.stream()
        .flatMapToInt(IntStream::of)
        .sum();
31
	                    
	                
	                    répondu
	                    Ward
	                    2017-12-28 19:36:11
	                
	            int sum = counts.stream().flatMapToInt(array -> IntStream.of(array)).sum();
14
	                    
	                
	                    répondu
	                    JB Nizet
	                    2017-12-28 19:35:10
	                
	            i est un tableau primitif (int[]), donc Stream.of(i) retour Stream<int[]>.
je vous suggère d'abord de calculer la somme de chaque tableau individuel et ensuite de les additionner tous:
int sum=counts.stream()
              .mapToInt(ar->IntStream.of(ar).sum()) // convert each int[] to the sum 
                                                    // of that array and transform the
                                                    // Stream to an IntStream
              .sum(); // calculate the total sum
7
	                    
	                
	                    répondu
	                    Eran
	                    2017-12-28 20:10:48
	                
	            Vous pouvez le faire de cette façon:
int sum = counts.stream()                               // getting Stream<int[]>
                .mapToInt(a -> Arrays.stream(a).sum())  // getting an IntStream with the sum of every int[]
                .sum();                                 // getting the total sum of all values.
5
	                    
	                
	                    répondu
	                    Juan Carlos Mendoza
	                    2017-12-29 13:24:19
	                
	            Cela a fonctionné pour moi:
int sum = counts.stream().mapToInt(i -> Arrays.stream(i).sum()).sum();
2
	                    
	                
	                    répondu
	                    Cardinal System
	                    2017-12-28 19:47:10