Example usage for java.util List parallelStream

List of usage examples for java.util List parallelStream

Introduction

In this page you can find the example usage for java.util List parallelStream.

Prototype

default Stream<E> parallelStream() 

Source Link

Document

Returns a possibly parallel Stream with this collection as its source.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Person> persons = Arrays.asList(new Person("Max", 18), new Person("Peter", 23),
            new Person("Pamela", 23), new Person("David", 12));

    Integer ageSum = persons.parallelStream().reduce(0, (sum, p) -> {
        System.out.format("accumulator: sum=%s; person=%s; thread=%s\n", sum, p,
                Thread.currentThread().getName());
        return sum += p.age;
    }, (sum1, sum2) -> {//from ww  w.  j  av  a  2 s.co  m
        System.out.format("combiner: sum1=%s; sum2=%s; thread=%s\n", sum1, sum2,
                Thread.currentThread().getName());
        return sum1 + sum2;
    });

    System.out.println(ageSum);
}

From source file:com.bobby.peng.learning.java.stream.StreamMap.java

public static void main(String[] args) {
    //        List<Integer> list = StreamMap.newRandomList();
    ///*  www.j  a  v  a 2 s . co m*/
    //        List<Integer> list2 = list.stream().map(i->i*5).collect(Collectors.toList());
    //
    //        StreamMap.printOut(list2);
    //
    //        list = list.subList(0,11);
    //        StreamMap.printOut(list);
    //
    //        String value = "INSERT INTO tech_subao_00.subao_renew_list (id, extra_info, gmt_created, gmt_modified, is_deleted, creator, modifier, remark, status, unqiue_flag, list_biz_id, province_name, province_code, city_name, city_code, license_no, engine_no, frame_no, factory_plate_model, first_register_date, applicant_name, owner_name, owner_certificate_type, owner_id_no, owner_mobile, contact_phone1, contact_phone2, bi_end_date, ci_end_date, vehicle_id, list_allocation_time, booking_start_date, booking_end_date, user_id, renew_batch_id, renew_biz_name, source, organization_id) VALUES (%d, null, '2018-08-07 02:50:36', '2018-08-07 02:50:37', 'N', '', 'system', null, 10, '000000%d', '1', '', '110000', '', '110100', '12312313', '12313', '31231', '111', '2018-05-12', '123', '123', 1, '310111111111111111', '13311111111', '13311111111', '13311111111', '2019-08-07 05:24:56', '2019-08-07 05:25:03', 1, null, null, null, null, %d, 'batch1', 50, 1);";
    //
    //        int id = 3;
    //        for(int i=3;i<100;i++) {
    //            for(int j=0;j<2;j++) {
    //                System.out.println(String.format(value,id,id,i));
    //                id++;
    //            }
    //        }

    List<Integer> test = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        test.add(i);
    }

    test.parallelStream().map(i -> {
        System.out.println(i);
        return i;
    }).collect(Collectors.toList());

    System.out.println("===================================");

    test.stream().map(i -> {
        System.out.println(i);
        return i;
    }).collect(Collectors.toList());

}

From source file:Main.java

public static void main(String[] args) {
    List<Person> roster = createRoster();
    ConcurrentMap<Person.Sex, List<Person>> byGenderParallel = roster.parallelStream()
            .collect(Collectors.groupingByConcurrent(Person::getGender));

    List<Map.Entry<Person.Sex, List<Person>>> byGenderList = new ArrayList<>(byGenderParallel.entrySet());

    System.out.println("Group members by gender:");
    byGenderList.stream().forEach(e -> {
        System.out.println("Gender: " + e.getKey());
        e.getValue().stream().map(Person::getName).forEach(f -> System.out.println(f));
    });//from   ww w.ja v a2 s.co  m

}

From source file:Main.java

public static void main(String[] args) {
    List<String> strings = new LinkedList<>();
    strings.add("a");
    strings.add("B");
    strings.add("ab");
    strings.add("abc");
    strings.add("ABC");

    ConcurrentMap<Integer, List<String>> byLength = strings.parallelStream()
            .collect(Collectors.groupingByConcurrent(String::length));

    System.out.println(byLength);
}

From source file:Main.java

public static void main(String[] args) {
    Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8 };
    List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));

    List<Integer> serialStorage = new ArrayList<>();

    System.out.println("Serial stream:");
    listOfIntegers.stream()/*from   w  w w  .  j a  v a 2  s. com*/

            // Don't do this! It uses a stateful lambda expression. 
            .map(e -> {
                serialStorage.add(e);
                return e;
            })

            .forEachOrdered(e -> System.out.print(e + " "));
    System.out.println("");

    serialStorage.stream().forEachOrdered(e -> System.out.print(e + " "));
    System.out.println("");

    System.out.println("Parallel stream:");
    List<Integer> parallelStorage = Collections.synchronizedList(new ArrayList<>());
    listOfIntegers.parallelStream()

            // Don't do this! It uses a stateful lambda expression.
            .map(e -> {
                parallelStorage.add(e);
                return e;
            })

            .forEachOrdered(e -> System.out.print(e + " "));
    System.out.println("");

    parallelStorage.stream().forEachOrdered(e -> System.out.print(e + " "));
    System.out.println("");

}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(//from   www .j  a  va  2  s.  co m
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:asia.gkc.vneedu.utils.FilterUtil.java

public static Map<String, Object> exclude(List<String> list, Map<String, Object> object) {
    list.parallelStream().forEach((e) -> object.remove(e.trim()));
    return object;
}

From source file:com.firewallid.util.FIUtils.java

public static <L> Map<L, Long> reduceListToMap(List<L> l) {
    Map<L, Long> map = l.parallelStream()
            .collect(Collectors.groupingBy(object -> object, Collectors.counting()));

    return map;/*from ww w  .jav a  2  s . co m*/
}

From source file:org.cripac.isee.vpe.ctrl.ConfManager.java

private static void prepareTmpCfgFiles() {
    tmpDir = System.getProperty("java.io.tmpdir");
    List<FileDescriptor> fileList = ConfManager.getCfgFileList(PedestrianTrackingApp.APP_NAME);
    fileList.parallelStream().forEach(file -> {
        File tmp = new File(tmpDir + "/" + file.getConcatName());
        try {// w ww  . j  a  v a2 s  . com
            tmp.createNewFile();
            tmp.deleteOnExit();
            FileOutputStream tmpOutputStream = new FileOutputStream(tmp);
            IOUtils.copy(new FileInputStream(CONF_DIR + "/" + file.getPath()), tmpOutputStream);
            tmpOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}

From source file:ru.VirtaMarketAnalyzer.main.Wizard.java

public static void saveProductImg(final List<Product> products) {
    products.parallelStream().forEach(product -> {
        saveImg(product.getImgUrl());/*  w  w  w.ja  v a  2 s. c o  m*/
        saveImg(product.getImgUrl().replace("/img/products/", "/img/products/16/"));
    });
}