@Override public final Double apply( final Stream<? extends ITerm> p_first, final Stream<? extends ITerm> p_second) { return this.ncd( p_first.map(Object::toString).collect(Collectors.joining("")), p_second.map(Object::toString).collect(Collectors.joining(""))); }
public static void main(String[] args) throws IOException { try (Stream<Path> stream = Files.list(Paths.get(""))) { String joined = stream .map(String::valueOf) .filter(path -> !path.startsWith(".")) .sorted() .collect(Collectors.joining("; ")); System.out.println("List: " + joined); } Path start = Paths.get(""); int maxDepth = 5; try (Stream<Path> stream = Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".java"))) { String joined = stream.sorted().map(String::valueOf).collect(Collectors.joining("; ")); System.out.println("Found: " + joined); } try (Stream<Path> stream = Files.walk(start, maxDepth)) { String joined = stream .map(String::valueOf) .filter(path -> path.endsWith(".java")) .sorted() .collect(Collectors.joining("; ")); System.out.println("walk(): " + joined); } List<String> lines = Files.readAllLines(Paths.get("src/golf.sh")); lines.add("puts 'foobar'"); Path path = Paths.get("src/golf-modified.sh"); Files.write(path, lines); try (Stream<String> stream = Files.lines(path)) { stream.filter(line -> line.contains("puts")).map(String::trim).forEach(System.out::println); } System.out.println("a" == "a"); System.out.println("a" != new String("a")); System.out.println(null != "a"); System.out.println("a".equals("a")); try (BufferedReader reader = Files.newBufferedReader(path)) { while (reader.ready()) System.out.println(reader.readLine()); } try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("hello-world.sh"))) { writer.write("puts 'Hello world'"); } try (BufferedReader reader = Files.newBufferedReader(path)) { long countPuts = reader.lines().filter(line -> line.contains("put")).count(); System.out.println(countPuts); } }
public void testUncheckedIOException() throws IOException { Path triggerFile = testFolder.resolve(Paths.get("dir2", "IOException")); Files.createFile(triggerFile); Path triggerDir = testFolder.resolve(Paths.get("empty", "IOException")); Files.createDirectories(triggerDir); Files.createFile(triggerDir.resolve("file")); FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance(); FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(testFolder, null); try { fsp.setFaultyMode(false); Path fakeRoot = fs.getRoot(); try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) { // only one file s.forEach(path -> assertEquals(path.getFileName().toString(), "IOException")); } try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); // ordered as depth-first assertEquals(result, new String[] {"empty", "IOException", "file"}); } fsp.setFaultyMode(true); try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) { s.forEach(path -> fail("should have caused exception")); } catch (UncheckedIOException uioe) { assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException); } try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to IOException"); } catch (UncheckedIOException uioe) { assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException); } try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty").resolve("IOException"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to IOException"); } catch (IOException ioe) { assertTrue(ioe instanceof FaultyFileSystem.FaultyException); } catch (UncheckedIOException ex) { fail("Top level should be repored as is"); } } finally { // Cleanup if (fs != null) { fs.close(); } Files.delete(triggerFile); TestUtil.removeAll(triggerDir); } }
public static <T> String listToString(Iterable<T> elements, String sep) { if (elements == null) throw new IllegalArgumentException("elements cannot be null."); Stream<T> stream = StreamSupport.stream(elements.spliterator(), false); return stream.map(a -> a.toString()).collect(Collectors.joining(sep)); }
public static void main(String... args) { /* ------------------------------------------------------------------------- From obj to ... ------------------------------------------------------------------------- */ Stream<String> streamOfStrings = Stream.of("un", "deux", "trois"); Function<String, StringBuilder> function = StringBuilder::new; streamOfStrings.map(function) /*.forEach(System.out::println)*/; streamOfStrings = Stream.of("un", "deux", "trois"); ToIntFunction<String> toIntFunction = String::length; IntStream streamOfInts = streamOfStrings.mapToInt(toIntFunction); streamOfStrings = Stream.of("un", "deux", "trois"); ToDoubleFunction<String> toDoubleFunction = String::length; DoubleStream streamOfDoubles = streamOfStrings.mapToDouble(toDoubleFunction); streamOfStrings = Stream.of("un", "deux", "trois"); ToLongFunction<String> toLongFunction = String::length; LongStream streamOfLongs = streamOfStrings.mapToLong(toLongFunction); /* ------------------------------------------------------------------------- From int to ... ------------------------------------------------------------------------- */ IntUnaryOperator plusplus = i -> i++; IntStream.of(1, 2, 3).map(plusplus) /*.forEach(x->System.out.println(x))*/ ; IntFunction<String> intFunction = i -> "" + i; IntStream.of(1, 2, 3).mapToObj(intFunction) /*.forEach(System.out::println)*/ ; IntToDoubleFunction itdf = i -> i; IntStream.of(1, 2, 3).mapToDouble(itdf) /*.forEach(System.out::println)*/ ; IntToLongFunction itlf = i -> i; IntStream.of(1, 2, 3).mapToLong(itlf) /*.forEach(System.out::println)*/ ; /* ------------------------------------------------------------------------- From long to ... ------------------------------------------------------------------------- */ LongUnaryOperator times = l -> l * l; LongStream.of(1L, 2L, 3L).map(times) /*.forEach(System.out::println)*/ ; LongFunction<String> lf = l -> "toto"; LongStream.of(1L, 2L, 3L).mapToObj(lf); /* ------------------------------------------------------------------------- From double to ... ------------------------------------------------------------------------- */ DoubleToIntFunction dtif = d -> (int) d; DoubleStream.of(1.3, 1.5, 1.6).mapToInt(dtif).forEach(System.out::println); }
@Override public TurnOption requestPlayerChoiceForTurn( Set<TurnOption> possibleActions, Player player, int remainingMoves) { Stream<TurnOption> sortedOptions = possibleActions .stream() .sorted((option1, option2) -> option1.toString().compareTo(option2.toString())); TurnOption[] sortedOptionsArray = (TurnOption[]) sortedOptions.toArray(); return sortedOptionsArray[this.selectOptionFromList(sortedOptions.map(TurnOption::toString))]; }
public Commit(de.fau.osr.core.vcs.base.Commit commit) { this.id = commit.getId(); this.message = commit.getMessage(); this.instanceRequirement = null; commitFiles = () -> { Stream<de.fau.osr.core.vcs.base.CommitFile> originalStream = commit.commitFiles.get(); // convert the commitFiles from the backend return originalStream.map(commitFile -> new PathDE(commitFile.newPath.toPath())); }; }
/** Reference to constructor */ @Test public void lambdaExpression_constructorReferences() { List<String> names = Lists.newArrayList("Teuvo", "Ari", "Kristiina"); Stream<StringLengthComputer> counters = names.stream().map(StringLengthComputer::new); List<Integer> lengths = counters.map(StringLengthComputer::computeLength).collect(Collectors.toList()); assertEquals(Lists.newArrayList(5, 3, 9), lengths); }
/** Wrap a Stream into a SimpleReactStream. */ static <T> SimpleReactStream<T> of(Stream<T> stream) { if (stream instanceof FutureStream) stream = ((FutureStream) stream).toQueue().stream(((FutureStream) stream).getSubscription()); SimpleReact sr = new SimpleReact( ThreadPools.getSequential(), RetryBuilder.getDefaultInstance().withScheduler(ThreadPools.getSequentialRetry()), false); return new SimpleReactStreamImpl<T>(sr, stream.map(CompletableFuture::completedFuture), null); }
/** * Returns a {@link List} of String arrays, each representing a line of text. * * @param pathToFile * @return */ List<String[]> readInputData(String pathToFile) { Stream<String> stream = getInputDataStream(pathToFile); List<String[]> list = stream .map( l -> { return (String[]) l.split("[\\s]*\\,[\\s]*"); }) .collect(Collectors.toList()); return list; }
public static CompilationUnit[] parseICompilationUnitStream( Stream<ICompilationUnit> stream, IJavaProject javaProject) throws IOException, JavaModelException { // Sneaky.<JavaModelException> Throw(); // Sneaky.<IOException> Throw(); return stream .map(ICompilationUnit::getResource) .map(IResource::getLocationURI) .map(File::new) .map(Sneaky.unchecked(f -> SharedUtils.parseJavaSource(f, javaProject))) .filter(Objects::nonNull) .toArray(CompilationUnit[]::new); }
private List<DocumentationItemDTO> getDocumentation( List<Document> docs, String searchTerm, int maxResults) { Stream<DocumentationItem> documentationStream; if (searchTerm.isEmpty()) { documentationStream = documentationService.documentationForDocuments(docs, maxResults).stream(); } else { documentationStream = documentationService.searchDocumentation(searchTerm, docs, maxResults).stream(); } return documentationStream .map(Transformations::convertDocumentationItemToDTO) .collect(Collectors.toList()); }
public static void main(String[] args) { Stream<Double> piStream = Stream.generate(new PiSupplier()); piStream.skip(1000000).limit(10).forEach(System.out::println); System.out.println("-------------------------------------------"); Stream<Double> piStream_1 = Stream.generate(new PiSupplier()); piStream_1 .map(new EulerTransform()) .map(new EulerTransform()) .map(new EulerTransform()) .map(new EulerTransform()) .map(new EulerTransform()) .map(new EulerTransform()) .skip(10) .limit(20) .forEach(System.out::println); }
public Analyze() throws IOException { Stream<String> lines = Files.lines(Paths.get(Break.LOCATION + "/result")); Stream<Result> s = lines.map(this::parseLine); System.out.println("Searching ..."); FrequencyAnalysis frequencyAnalysis = new FrequencyAnalysis(FrequencyAnalysis.simple(), 0.8); Map<Break.Setup, String> answers = s.filter(result -> frequencyAnalysis.analyse(result.line)) // .filter(result -> // frequencyAnalysis.containsKeywords(result.line)) .collect(Collectors.toMap(r -> r.setup, r -> r.line)); System.out.println("Found " + answers.values().size()); answers.forEach( (k, v) -> { System.out.println(k + " -> " + v); }); if (answers.isEmpty()) { throw new IllegalStateException("Did not find anything ..."); } }
@Override public Object map(Stream t, Function fn) { return t.map(fn); }
@Override public Stream<String> apply(Stream<String> input) { return input.map(s -> s.replaceAll(regexp, replacement)); }
public void testSecurityException() throws IOException { Path empty = testFolder.resolve("empty"); Path triggerFile = Files.createFile(empty.resolve("SecurityException")); Path sampleFile = Files.createDirectories(empty.resolve("sample")); Path dir2 = testFolder.resolve("dir2"); Path triggerDir = Files.createDirectories(dir2.resolve("SecurityException")); Files.createFile(triggerDir.resolve("fileInSE")); Path sample = Files.createFile(dir2.resolve("file")); Path triggerLink = null; Path linkTriggerDir = null; Path linkTriggerFile = null; if (supportsLinks) { Path dir = testFolder.resolve("dir"); triggerLink = Files.createSymbolicLink(dir.resolve("SecurityException"), empty); linkTriggerDir = Files.createSymbolicLink(dir.resolve("lnDirSE"), triggerDir); linkTriggerFile = Files.createSymbolicLink(dir.resolve("lnFileSE"), triggerFile); } FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance(); FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(testFolder, null); try { fsp.setFaultyMode(false); Path fakeRoot = fs.getRoot(); // validate setting try (Stream<Path> s = Files.list(fakeRoot.resolve("empty"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder(result, new String[] {"SecurityException", "sample"}); } try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir2"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder(result, new String[] {"dir2", "SecurityException", "fileInSE", "file"}); } if (supportsLinks) { try (Stream<Path> s = Files.list(fakeRoot.resolve("dir"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder( result, new String[] {"d1", "f1", "lnDir2", "SecurityException", "lnDirSE", "lnFileSE"}); } } // execute test fsp.setFaultyMode(true); // ignore file cause SecurityException try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder(result, new String[] {"empty", "sample"}); } // skip folder cause SecurityException try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir2"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder(result, new String[] {"dir2", "file"}); } if (supportsLinks) { // not following links try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder( result, new String[] {"dir", "d1", "f1", "lnDir2", "lnDirSE", "lnFileSE"}); } // following links try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir"), FileVisitOption.FOLLOW_LINKS)) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); // ?? Should fileInSE show up? // With FaultyFS, it does as no exception thrown for link to "SecurityException" with read // on "lnXxxSE" assertEqualsNoOrder( result, new String[] { "dir", "d1", "f1", "lnDir2", "file", "lnDirSE", "lnFileSE", "fileInSE" }); } } // list instead of walk try (Stream<Path> s = Files.list(fakeRoot.resolve("empty"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder(result, new String[] {"sample"}); } try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); assertEqualsNoOrder(result, new String[] {"file"}); } // root cause SecurityException should be reported try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir2").resolve("SecurityException"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to SecurityException"); } catch (SecurityException se) { assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException); } // Walk a file cause SecurityException, we should get SE try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir").resolve("SecurityException"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to SecurityException"); } catch (SecurityException se) { assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException); } // List a file cause SecurityException, we should get SE as cannot read attribute try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2").resolve("SecurityException"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to SecurityException"); } catch (SecurityException se) { assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException); } try (Stream<Path> s = Files.list(fakeRoot.resolve("dir").resolve("SecurityException"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to SecurityException"); } catch (SecurityException se) { assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException); } } finally { // Cleanup if (fs != null) { fs.close(); } if (supportsLinks) { Files.delete(triggerLink); Files.delete(linkTriggerDir); Files.delete(linkTriggerFile); } Files.delete(triggerFile); Files.delete(sampleFile); Files.delete(sample); TestUtil.removeAll(triggerDir); } }
@SuppressWarnings("unchecked") public static void main(String... args) throws Exception { Stream<String> scrabbleWordsStream = Files.lines(Paths.get("files", "ospd.txt")); Set<String> scrabbleWords = scrabbleWordsStream.map(String::toLowerCase).collect(Collectors.toSet()); Stream<String> shakespeareWordsStream = Files.lines(Paths.get("files", "words.shakespeare.txt")); Set<String> shakespeareWords = shakespeareWordsStream.map(String::toLowerCase).collect(Collectors.toSet()); System.out.println("# de mots autorisés au Scrabble : " + scrabbleWords.size()); // mots utilisés par Shakespeare Long nWords1 = shakespeareWords.stream().count(); System.out.println("# ofmots utilisés par Shakespeare : " + nWords1); // number of words used by Shakespeare and allowed at Scrabble long count = shakespeareWords.stream().map(String::toLowerCase).filter(scrabbleWords::contains).count(); System.out.println("# number of words used by Shakespeare and allowed at Scrabble = " + count); // words of Shakespeare grouped by their length Map<Integer, Long> map1 = shakespeareWords .stream() .collect(Collectors.groupingBy(String::length, Collectors.counting())); System.out.println("Words of Shakespeare grouped by their length = " + map1); // words of Shakespeare of 16 letters and more Map<Integer, List<String>> map2 = shakespeareWords .stream() .filter(word -> word.length() > 15) .collect(Collectors.groupingBy(String::length)); System.out.println("Words of Shakespeare of 16 letters and more = " + map2); // words of Shakespeare grouped by their Scrabble score // in ascending order Function<String, Integer> score = word -> word.chars().map(scrabbleLetterValueEN).sum(); Map<Integer, Long> map3 = shakespeareWords .stream() .map(String::toLowerCase) .filter(scrabbleWords::contains) .collect(Collectors.groupingBy(score, TreeMap::new, Collectors.counting())); System.out.println("Words of Shakespeare grouped by their Scrabble score = " + map3); // words of Shakespeare grouped by their Scrabble score, with a score greater than 29 // in ascending order Predicate<String> scoreGT28 = word -> score.apply(word) > 28; Map<Integer, List<String>> map4 = shakespeareWords .stream() .map(String::toLowerCase) .filter(scrabbleWords::contains) .filter(scoreGT28) .collect(Collectors.groupingBy(score, TreeMap::new, Collectors.toList())); System.out.println("Words of Shakespeare grouped by their Scrabble score = " + map4); // histogram of the letters in a given word Function<String, Map<Integer, Long>> lettersHisto = word -> word.chars() .mapToObj(Integer::new) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); // score of a given word, taking into account that the given word // might contain blank letters Function<String, Integer> scoreWithBlanks = word -> lettersHisto .apply(word) .entrySet() .stream() // Map.Entry<letters, # used> .mapToInt( entry -> scrabbleENScore[entry.getKey() - 'a'] * (int) Long.min( entry.getValue(), scrabbleENDistribution[entry.getKey() - 'a'])) .sum(); // number of blanks used for the given word Function<String, Integer> blanksUsed = word -> lettersHisto .apply(word) .entrySet() .stream() // Map.Entry<letters, # used> .mapToInt( entry -> (int) Long.max( 0L, entry.getValue() - scrabbleENDistribution[entry.getKey() - 'a'])) .sum(); System.out.println("Number of blanks in [buzzards] = " + blanksUsed.apply("buzzards")); System.out.println("Real score of [buzzards] = " + scoreWithBlanks.apply("buzzards")); System.out.println("Number of blanks in [whizzing] = " + blanksUsed.apply("whizzing")); System.out.println("Real score of [whizzing] = " + scoreWithBlanks.apply("whizzing")); // best words of Shakespeare and their scores Map<Integer, List<String>> map = shakespeareWords .stream() .filter(scrabbleWords::contains) .filter(word -> blanksUsed.apply(word) <= 2L) .filter(word -> scoreWithBlanks.apply(word) >= 24) .collect(Collectors.groupingBy(scoreWithBlanks, Collectors.toList())); System.out.println("Best words of Shakespeare : " + map); }
@Override public Stream<String> apply(Stream<String> input) { return input.map(Functions.cut(delimiter, field)); }
default <R> SimpleReactStream<R> fromStream(Stream<R> stream) { return (SimpleReactStream<R>) this.withLastActive( getLastActive().withNewStream(stream.map(CompletableFuture::completedFuture))); }
static void filesTest() { // Files.list try { try (Stream<Path> stream = Files.list(Paths.get("/opt"))) { String joined = stream .map(String::valueOf) .filter(path -> !path.startsWith(".")) .sorted() .collect(Collectors.joining("; ")); System.out.println("List path /opt : " + joined); } } catch (IOException e) { e.printStackTrace(); } // Files.find Path start = Paths.get("/Users/alibaba/Downloads/2016113"); int maxDepth = 5; try (Stream<Path> stream = Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".js"))) { String joined = stream.sorted().map(String::valueOf).collect(Collectors.joining("; ")); System.out.println("Files find : " + joined); } catch (IOException e) { e.printStackTrace(); } // Files.walk try (Stream<Path> stream = Files.walk(start, maxDepth)) { String joined = stream .map(String::valueOf) .filter(path -> path.endsWith(".js")) .sorted() .collect(Collectors.joining("; ")); System.out.println("Files walk : " + joined); } catch (IOException e) { e.printStackTrace(); } // Files.readAllLines try { String p = "/Users/alibaba/linuxsir.txt"; List<String> lines = Files.readAllLines(Paths.get(p)); lines.add("print('foobar');"); Files.write(Paths.get(p), lines); lines.remove(lines.size() - 1); System.out.println("readAllLines " + lines); Files.write(Paths.get(p), lines); } catch (IOException e) { e.printStackTrace(); } // Files.lines try (Stream<String> stream = Files.lines(Paths.get("/Users/alibaba/linuxsir.txt"))) { stream.filter(line -> line.contains("w")).map(String::valueOf).forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } // Files.newBufferedReader&Files.newBufferedWriter Path path = Paths.get("/Users/alibaba/linuxsir.txt"); try (BufferedReader reader = Files.newBufferedReader(path)) { System.out.println(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } path = Paths.get("/Users/alibaba/output.txt"); try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write("print('Hello World')"); } catch (IOException e) { e.printStackTrace(); } }
@Override public Stream<String> apply(Stream<T> input) { return input.map(Object::toString); }
private Stream<Optional<JobClass_old>> getStreamJobClasses(Stream<String> strmJobID) { return strmJobID.map(j -> lstClass.stream().filter(job -> job.getId().equals(j)).findAny()); }