Example usage for java.util Set parallelStream

List of usage examples for java.util Set parallelStream

Introduction

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

Prototype

default Stream<E> parallelStream() 

Source Link

Document

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

Usage

From source file:HSqlManager.java

public static void primerAnalysis(Connection connection, int bps) throws SQLException, IOException {
    long time = System.currentTimeMillis();
    DpalLoad.main(new String[1]);
    HSqlPrimerDesign.Dpal_Inst = DpalLoad.INSTANCE_WIN64;
    String base = new File("").getAbsolutePath();
    CSV.makeDirectory(new File(base + "/PhageData"));
    INSTANCE = ImportPhagelist.getInstance();
    INSTANCE.parseAllPhages(bps);/*  ww w .jav  a2s.c o m*/
    System.out.println((System.currentTimeMillis() - time) / Math.pow(10, 3) / 60);
    time = System.currentTimeMillis();
    written = true;
    Connection db = connection;
    db.setAutoCommit(false);
    Statement stat = db.createStatement();
    stat.execute("SET FILES LOG FALSE\n");
    //        PreparedStatement st = db.prepareStatement("Insert INTO Primerdb.Primers" +
    //                "(Bp,Sequence, CommonP, UniqueP, Picked, Strain, Cluster)" +
    //                " Values(?,?,true,false,false,?,?)");
    PreparedStatement st = db.prepareStatement(
            "INSERT INTO Primerdb.Primers" + "(Bp,Sequence,Strain,Cluster,Tm,GC,UniqueP,CommonP,Hairpin) "
                    + "VALUES(?,?,?,?,?,?,true,true,?)");
    ResultSet call = stat.executeQuery("Select * From Primerdb.Phages;");
    List<String[]> phages = new ArrayList<>();
    while (call.next()) {
        String[] r = new String[3];
        r[0] = call.getString("Strain");
        r[1] = call.getString("Cluster");
        r[2] = call.getString("Name");
        phages.add(r);

        //            if(strain.equals("-myco")) {
        //                if (r[2].equals("xkcd")) {
        //                    strain = r[0];
        //                }
        //            }else if(strain.equals("-arthro")){
        //                if (r[2].equals("ArV1")) {
        //                    strain = r[0];
        //                }
        //            }
    }
    call.close();

    Set<String> strains = phages.stream().map(y -> y[0]).collect(Collectors.toSet());
    for (String x : strains) {
        Set<String> clust = phages.stream().filter(y -> y[0].equals(x)).map(y -> y[1])
                .collect(Collectors.toSet());
        Map<String, Integer> clustersNum = new HashMap<>();
        Map<Integer, String> clustersName = new HashMap<>();
        Map<Integer, List<String>> clusters = new HashMap<>();
        Map<Bytes, Primer> primers = new HashMap<>();
        int i = 0;
        for (String cluster : clust) {
            clustersName.put(i, cluster);
            clustersNum.put(cluster, i);
            i++;
        }
        clust.parallelStream()
                .forEach(cluster -> clusters.put(clustersNum.get(cluster),
                        phages.stream().filter(a -> a[0].equals(x) && a[1].equals(cluster)).map(a -> a[2])
                                .collect(Collectors.toList())));
        for (int z : clusters.keySet()) {
            //            try {
            List<String> clustphages = clusters.get(z);
            for (String phage : clustphages) {
                Set<Bytes> phagprimers =
                        //Read from CSV file here
                        //Premade CSV files of all possible
                        //primers in a phage genome
                        CSV.readCSV(base + "/PhageData/" + Integer.toString(bps) + phage + ".csv").stream()
                                .map(l -> new Bytes(l.getBytes())).collect(Collectors.toSet());
                for (Bytes primer : phagprimers) {
                    if (!primers.containsKey(primer)) {
                        primers.put(primer, new Primer(z));
                    } else {
                        Primer select = primers.get(primer);
                        select.phageCount++;
                        if (!select.containsCluster(z)) {
                            select.addCluster(z);
                        }
                    }

                }

            }
            System.out.println(clustersName.get(z));
        }
        int count = 0;
        Iterator<Map.Entry<Bytes, Primer>> primersSet = primers.entrySet().iterator();
        while (primersSet.hasNext()) {
            Map.Entry<Bytes, Primer> primer = primersSet.next();
            Primer primerInf = primer.getValue();
            if (primerInf.clusters.length != 1) {
                primer.setValue(null);
            } else {
                int primerClust = -1;
                for (int cluster : primerInf.clusters) {
                    primerClust = cluster;
                }
                if (primerInf.phageCount != clusters.get(primerClust).size()) {
                    primer.setValue(null);
                } else {
                    count++;
                }
            }
        }
        System.out.print("Unique Count: ");
        System.out.println(count);
        System.out.print("Primer Count: ");
        System.out.println(primers.size());
        i = 0;
        for (Bytes a : primers.keySet()) {
            Primer primerInf = primers.get(a);
            if (primerInf != null) {
                String primerClust = "";
                for (int cluster : primerInf.clusters) {
                    primerClust = clustersName.get(cluster);
                }
                String str = new String(a.bytes);
                try {
                    st.setInt(1, bps);
                    st.setString(2, str);
                    st.setString(3, x);
                    st.setString(4, primerClust);
                    //                        st.setDouble(5, HSqlPrimerDesign.primerTm(str, 0, 800, 1.5, 0.2));
                    st.setDouble(5, HSqlPrimerDesign.easytm(str));
                    st.setDouble(6, HSqlPrimerDesign.gcContent(str));
                    st.setBoolean(7, HSqlPrimerDesign.calcHairpin(str, 4));
                    st.addBatch();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("Error occurred at " + x + " " + primerClust);
                }
                i++;
                if (i == 1000) {
                    i = 0;
                    st.executeBatch();
                    db.commit();
                }
            }
        }
        if (i > 0) {
            st.executeBatch();
            db.commit();
        }

        //        }

        System.out.println("Unique Updated");
        System.out.println((System.currentTimeMillis() - time) / Math.pow(10, 3) / 60);
    }
    stat.execute("SET FILES LOG TRUE;");
    st.close();
    stat.close();
}

From source file:com.fitbur.testify.di.spring.SpringServiceLocator.java

@Override
public <T> T getService(Type type, Set<? extends Annotation> annotations) {
    TypeToken<?> token = TypeToken.of(type);

    Object instance;//from  w  w w. ja  v a2  s. co m
    Optional<Class<? extends Annotation>> beanAnnotation = empty();
    Class rawType = token.getRawType();

    Optional<String> beanName = annotations.parallelStream()
            .filter(p -> p.annotationType().equals(Qualifier.class)).map(Qualifier.class::cast)
            .map(Qualifier::value).findFirst();

    if (!beanName.isPresent()) {
        beanName = annotations.parallelStream().filter(p -> p.annotationType().equals(Named.class))
                .map(Named.class::cast).map(Named::value).findFirst();
    }

    if (!beanName.isPresent()) {
        Set<Class<? extends Annotation>> customQualfiers = serviceAnnotations.getCustomQualifiers();

        for (Annotation annotation : annotations) {
            Class<? extends Annotation> annotationType = annotation.annotationType();

            for (Class<? extends Annotation> customQualfier : customQualfiers) {
                if (annotationType.isAnnotationPresent(customQualfier)
                        || annotationType.equals(Qualifier.class)) {
                    beanAnnotation = of(annotationType);
                    break;
                }
            }

            if (beanAnnotation.isPresent()) {
                break;
            }
        }
    }

    if (beanName.isPresent()) {
        String name = beanName.get();
        if (token.isSubtypeOf(Provider.class)) {
            TypeVariable<Class<Provider>> paramType = Provider.class.getTypeParameters()[0];
            rawType = token.resolveType(paramType).getRawType();
            instance = new ServiceProvider(this, name, rawType);
        } else if (token.isSubtypeOf(Optional.class)) {
            TypeVariable<Class<Optional>> paramType = Optional.class.getTypeParameters()[0];
            rawType = token.resolveType(paramType).getRawType();
            instance = Optional.ofNullable(context.getBean(name, rawType));
        } else {
            instance = context.getBean(name, rawType);
        }
    } else if (beanAnnotation.isPresent()) {
        Map<String, Object> beans = context.getBeansWithAnnotation(beanAnnotation.get());
        instance = beans.entrySet().parallelStream().map(p -> {
            Object value;
            if (token.isSubtypeOf(Provider.class)) {
                value = new ServiceProvider(this, p.getKey(), p.getValue().getClass());
            } else if (token.isSubtypeOf(Optional.class)) {
                value = of(p.getValue());
            } else {
                value = p.getValue();
            }

            return value;
        }).findFirst().get();
    } else {
        instance = getService(type);
    }

    return (T) instance;
}

From source file:fr.landel.utils.assertor.utils.AssertorMap.java

private static <M extends Map<K, V>, K, V, T> boolean hasInOrder(final M map, final Iterable<T> objects,
        final boolean not, final EnumAnalysisMode analysisMode,
        final BiPredicate<Entry<K, V>, T> entriesEqualChecker, final Class<T> objectsClass) {

    int found = 0;

    final int size1 = map.size();
    final int size2 = IterableUtils.size(objects);

    if (size1 < size2) {
        return not;
    }//from   w w  w . ja  va  2 s .  c o m

    final Set<Entry<K, V>> entries1 = map.entrySet();
    final List<T> entries2 = IterableUtils.toList(objects);

    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        for (Entry<K, V> entry1 : entries1) {
            if (found < size2) {
                if (entriesEqualChecker.test(entry1, entries2.get(found))) {
                    ++found;
                } else if (found > 0) {
                    found = 0;
                }
            }
        }
    } else {
        final AtomicInteger count = new AtomicInteger(0);

        final Stream<Entry<K, V>> stream;
        if (EnumAnalysisMode.PARALLEL.equals(analysisMode)) {
            stream = entries1.parallelStream();
        } else {
            stream = entries1.stream();
        }

        stream.forEachOrdered(o -> {
            int inc = count.get();
            if (inc < size2) {
                if (entriesEqualChecker.test(o, entries2.get(inc))) {
                    count.incrementAndGet();
                } else if (inc > 0) {
                    count.set(0);
                }
            }
        });

        found = count.get();
    }

    return not ^ (found == size2);
}

From source file:fr.landel.utils.assertor.utils.AssertorMap.java

private static <K, V> boolean match(final Map<K, V> map, final Predicate<Entry<K, V>> predicate,
        final boolean all, final EnumAnalysisMode analysisMode) {

    final Set<Entry<K, V>> entries = map.entrySet();

    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        if (all) {
            for (final Entry<K, V> entry : entries) {
                if (!predicate.test(entry)) {
                    return false;
                }//from ww  w.j  av a  2 s.  c om
            }
            return true;
        } else {
            for (final Entry<K, V> entry : entries) {
                if (predicate.test(entry)) {
                    return true;
                }
            }
            return false;
        }
    } else {
        final Stream<Entry<K, V>> stream;
        if (EnumAnalysisMode.PARALLEL.equals(analysisMode)) {
            stream = entries.parallelStream();
        } else {
            stream = entries.stream();
        }
        if (all) {
            return stream.allMatch(predicate);
        } else {
            return stream.anyMatch(predicate);
        }
    }
}

From source file:delfos.rs.trustbased.WeightedGraph.java

private double[][] makeMatrixFromEdges(Set<PathBetweenNodes<Node>> edges) {
    double[][] matrix = new double[nodesIndex.size()][nodesIndex.size()];
    edges.parallelStream().filter(edge -> Double.isFinite(edge.getLength())).forEach(edge -> {
        Integer fromIndex = nodesIndex.get(edge.from());
        Integer toIndex = nodesIndex.get(edge.to());
        double weight = Objects.equals(fromIndex, toIndex) ? 0 : edge.getFirstWeight();
        matrix[fromIndex][toIndex] = weight;
    });/* w ww  . java2s .  c om*/

    IntStream.range(0, matrix.length).boxed().parallel().forEach(index -> matrix[index][index] = 1);
    return matrix;
}

From source file:delfos.rs.trustbased.WeightedGraph.java

private void validateEdges(Set<PathBetweenNodes<Node>> edges) throws IllegalArgumentException {
    List<PathBetweenNodes<Node>> edgesWithMoreThanOneJump = edges.parallelStream()
            .filter(edge -> edge.numEdges() != 1).collect(Collectors.toList());

    if (!edgesWithMoreThanOneJump.isEmpty()) {
        System.out.println("There are edges that are paths!");
        edgesWithMoreThanOneJump.forEach(edge -> System.out.println(edge));
        throw new IllegalArgumentException(
                "The edges specified have more than one jump: " + edgesWithMoreThanOneJump.toString());
    }/* w w  w  .  ja  v  a2 s  .  c om*/
}

From source file:fastcall.FastCallSNP.java

private void fillDepthAndBase(ConcurrentHashMap<String, List<List<String>>> bamPileupResultMap,
        StringBuilder[][] baseSb, int[][] depth, int startPos) {
    Set<Map.Entry<String, String[]>> entries = this.taxaBamPathMap.entrySet();
    entries.parallelStream().forEach(e -> {
        String taxa = e.getKey();
        int taxaIndex = Arrays.binarySearch(this.taxaNames, taxa);
        String[] bams = e.getValue();

        int count = 0;
        String b = null;/*from w  w  w .ja v  a  2s .c  om*/
        try {
            for (int i = 0; i < bams.length; i++) {
                List<List<String>> lines = bamPileupResultMap.get(bams[i]);
                count = lines.size();
                b = bams[i];
                for (int j = 0; j < lines.size(); j++) {
                    List<String> split = lines.get(j);
                    if (split.get(2).startsWith("N") || split.get(2).startsWith("n"))
                        continue;
                    int siteIndex = Integer.valueOf(split.get(1)) - startPos;
                    depth[siteIndex][taxaIndex] += Integer.valueOf(split.get(3));
                    baseSb[siteIndex][taxaIndex].append(split.get(4));
                }
            }
        } catch (Exception ee) {
            System.out.println(b);
            System.out.println(count);
            ee.printStackTrace();
            System.exit(1);
        }
    });
}

From source file:fr.landel.utils.assertor.utils.AssertorMap.java

private static <M extends Map<K, V>, K, V> boolean contains(final M map, final Map<K, V> objects,
        final boolean all, final boolean not, final EnumAnalysisMode analysisMode) {

    final Set<Entry<K, V>> entries = objects.entrySet();
    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        if (all && !not) {
            for (final Entry<K, V> entry : entries) {
                if (!AssertorMap.contains(map, entry.getKey(), entry.getValue())) {
                    return false;
                }/*from   w  w w .  ja  va 2  s.  c  om*/
            }
            return true;
        } else if (!all) { // any and not any
            for (final Entry<K, V> entry : entries) {
                if (AssertorMap.contains(map, entry.getKey(), entry.getValue())) {
                    return !not;
                }
            }
            return not;
        } else { // not all
            long found = 0;
            for (final Entry<K, V> entry : entries) {
                if (AssertorMap.contains(map, entry.getKey(), entry.getValue())) {
                    ++found;
                }
            }
            return HelperAssertor.isValid(all, not, found, entries.size());
        }
    } else {
        final Stream<Entry<K, V>> stream;
        if (EnumAnalysisMode.PARALLEL.equals(analysisMode)) {
            stream = entries.parallelStream();
        } else {
            stream = entries.stream();
        }

        return HelperAssertor.isValid(stream, e -> AssertorMap.contains(map, e.getKey(), e.getValue()), all,
                not, objects::size);
    }
}

From source file:com.github.aptd.simulation.TestCLanguageLabels.java

/**
 * test-case all resource strings//from www  . ja v  a2s  .  c  o m
 *
 * @throws IOException throws on io errors
 */
@Test
public void testResourceString() throws IOException {
    assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty());

    final Set<String> l_ignoredlabel = new HashSet<>();

    // --- parse source and get label definition
    final Set<String> l_label = Collections.unmodifiableSet(Files.walk(Paths.get(SEARCHPATH))
            .filter(Files::isRegularFile).filter(i -> i.toString().endsWith(".java")).flatMap(i -> {
                try {
                    final CJavaVistor l_parser = new CJavaVistor();
                    l_parser.visit(JavaParser.parse(new FileInputStream(i.toFile())), null);
                    return l_parser.labels().stream();
                } catch (final IOException l_excpetion) {
                    assertTrue(MessageFormat.format("io error on file [{0}]: {1}", i, l_excpetion.getMessage()),
                            false);
                    return Stream.empty();
                } catch (final ParseProblemException l_exception) {
                    // add label build by class path to the ignore list
                    l_ignoredlabel.add(i.toAbsolutePath().toString()
                            // remove path to class directory
                            .replace(FileSystems.getDefault().provider().getPath(SEARCHPATH).toAbsolutePath()
                                    .toString(), "")
                            // string starts with path separator
                            .substring(1)
                            // remove file extension
                            .replace(".java", "")
                            // replace separators with dots
                            .replace("/", CLASSSEPARATOR)
                            // convert to lower-case
                            .toLowerCase()
                            // remove package-root name
                            .replace(CCommon.PACKAGEROOT + CLASSSEPARATOR, ""));

                    System.err.println(MessageFormat.format("parsing error on file [{0}]:\n{1}", i,
                            l_exception.getMessage()));
                    return Stream.empty();
                }
            }).collect(Collectors.toSet()));

    // --- check of any label is found
    assertFalse("translation labels are empty, check naming of translation method", l_label.isEmpty());

    // --- check label towards the property definition
    if (l_ignoredlabel.size() > 0)
        System.err.println(MessageFormat.format(
                "labels that starts with {0} are ignored, because parsing errors are occurred",
                l_ignoredlabel));

    LANGUAGEPROPERY.forEach((k, v) -> {
        try {
            final Properties l_property = new Properties();
            l_property.load(new FileInputStream(new File(v)));

            final Set<String> l_parseditems = new HashSet<>(l_label);
            final Set<String> l_propertyitems = l_property.keySet().parallelStream().map(Object::toString)
                    .collect(Collectors.toSet());

            // --- check if all property items are within the parsed labels
            l_parseditems.removeAll(l_propertyitems);
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the language file:\n{2}",
                    k, l_parseditems.size(), StringUtils.join(l_parseditems, ", ")), l_parseditems.isEmpty());

            // --- check if all parsed labels within the property item and remove ignored labels
            l_propertyitems.removeAll(l_label);
            final Set<String> l_ignoredpropertyitems = l_propertyitems.parallelStream()
                    .filter(j -> l_ignoredlabel.parallelStream().map(j::startsWith).allMatch(l -> false))
                    .collect(Collectors.toSet());
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the source code:\n{2}",
                    k, l_ignoredpropertyitems.size(), StringUtils.join(l_ignoredpropertyitems, ", ")),
                    l_ignoredpropertyitems.isEmpty());
        } catch (final IOException l_exception) {
            assertTrue(MessageFormat.format("io exception: {0}", l_exception.getMessage()), false);
        }
    });
}

From source file:de.flashpixx.rrd_antlr4.TestCLanguageLabels.java

/**
 * test-case all resource strings/*from ww w.j a  v a 2 s  .co  m*/
 *
 * @throws IOException throws on io errors
 */
@Test
public void testResourceString() throws IOException {
    assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty());

    final Set<String> l_ignoredlabel = new HashSet<>();

    // --- parse source and get label definition
    final Set<String> l_label = Collections.unmodifiableSet(Files.walk(Paths.get(SEARCHPATH))
            .filter(Files::isRegularFile).filter(i -> i.toString().endsWith(".java")).flatMap(i -> {
                try {
                    final CJavaVistor l_parser = new CJavaVistor();
                    l_parser.visit(JavaParser.parse(new FileInputStream(i.toFile())), null);
                    return l_parser.labels().stream();
                } catch (final IOException l_excpetion) {
                    assertTrue(MessageFormat.format("io error on file [{0}]: {1}", i, l_excpetion.getMessage()),
                            false);
                    return Stream.<String>empty();
                } catch (final ParseException l_exception) {
                    // add label build by class path to the ignore list
                    l_ignoredlabel.add(i.toAbsolutePath().toString()
                            // remove path to class directory
                            .replace(FileSystems.getDefault().provider().getPath(SEARCHPATH).toAbsolutePath()
                                    .toString(), "")
                            // string starts with path separator
                            .substring(1)
                            // remove file extension
                            .replace(".java", "")
                            // replace separators with dots
                            .replace("/", CLASSSEPARATOR)
                            // convert to lower-case
                            .toLowerCase()
                            // remove package-root name
                            .replace(CCommon.PACKAGEROOT + CLASSSEPARATOR, ""));

                    System.err.println(MessageFormat.format("parsing error on file [{0}]:\n{1}", i,
                            l_exception.getMessage()));
                    return Stream.<String>empty();
                }
            }).collect(Collectors.toSet()));

    // --- check of any label is found
    assertFalse("translation labels are empty, check naming of translation method", l_label.isEmpty());

    // --- check label towards the property definition
    if (l_ignoredlabel.size() > 0)
        System.err.println(MessageFormat.format(
                "labels that starts with {0} are ignored, because parsing errors are occurred",
                l_ignoredlabel));

    LANGUAGEPROPERY.entrySet().forEach(i -> {
        try {
            final Properties l_property = new Properties();
            l_property.load(new FileInputStream(new File(i.getValue())));

            final Set<String> l_parseditems = new HashSet<>(l_label);
            final Set<String> l_propertyitems = l_property.keySet().parallelStream().map(Object::toString)
                    .collect(Collectors.toSet());

            // --- check if all property items are within the parsed labels
            l_parseditems.removeAll(l_propertyitems);
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the language file:\n{2}",
                    i.getKey(), l_parseditems.size(), StringUtils.join(l_parseditems, ", ")),
                    l_parseditems.isEmpty());

            // --- check if all parsed labels within the property item and remove ignored labels
            l_propertyitems.removeAll(l_label);
            final Set<String> l_ignoredpropertyitems = l_propertyitems.parallelStream()
                    .filter(j -> l_ignoredlabel.parallelStream().map(j::startsWith).allMatch(l -> false))
                    .collect(Collectors.toSet());
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the source code:\n{2}",
                    i.getKey(), l_ignoredpropertyitems.size(), StringUtils.join(l_ignoredpropertyitems, ", ")),
                    l_ignoredpropertyitems.isEmpty());
        } catch (final IOException l_exception) {
            assertTrue(MessageFormat.format("io exception: {0}", l_exception.getMessage()), false);
        }
    });
}