daily pastebin goal
78%
SHARE
TWEET

Untitled

a guest Mar 14th, 2018 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Random;
  4.  
  5. public class Reduce {
  6.     public static void main(String[] args) {
  7.         Random rnd = new Random();
  8.         List<Integer> input = new ArrayList<>();
  9.         for (int i = 0; i < 5; i++) {
  10.             input.add(rnd.nextInt(100));
  11.         }
  12.  
  13.         Data result = input.stream().reduce(new Data('a', new ArrayList<>()),
  14.                 (data, num) -> {
  15.                     data.list.add("" + num + data.letter);
  16.                     data.letter = (char) (data.letter + 1);
  17.                     return data;
  18.                 },
  19.                 (data1, data2) -> data1);
  20.         System.out.println(result.list);
  21.     }
  22. }
  23.  
  24. class ReduceImmutable {
  25.     public static void main(String[] args) {
  26.         Random rnd = new Random();
  27.         List<Integer> input = new ArrayList<>();
  28.         for (int i = 0; i < 5; i++) {
  29.             input.add(rnd.nextInt(100));
  30.         }
  31.  
  32.         Data result = input.stream().reduce(new Data('a', new ArrayList<>()),
  33.                 (data, num) -> {
  34.                     //consider class Data is immutable
  35.                     Data newAcc = new Data();
  36.                     List<String> newList = new ArrayList<>();
  37.                     newList.addAll(data.list);
  38.                     newList.add("" + num + data.letter);
  39.                     newAcc.letter = (char) (data.letter + 1);
  40.                     newAcc.list = newList;
  41.                     return newAcc;
  42.                 },
  43.                 (data1, data2) -> data1);
  44.         System.out.println(result.list);
  45.     }
  46. }
  47.  
  48. class Data {
  49.     char letter;
  50.     List<String> list;
  51.    
  52.     Data() {}
  53.  
  54.     Data(char letter, List<String> list) {
  55.         this.letter = letter;
  56.         this.list = list;
  57.     }
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top