Java Code Examples for java.util.List#stream()

The following examples show how to use java.util.List#stream() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public Stream<URL> locate(String profileName) throws IOException {
    List<URL> located = new ArrayList<>();

    Path path = this.root.resolve(PROJECT_PREFIX + profileName + ".yml");

    if (Files.exists(path)) {
        located.add(path.toUri().toURL());
    }

    path = this.root.resolve(PROJECT_PREFIX + profileName + ".yaml");

    if (Files.exists(path)) {
        located.add(path.toUri().toURL());
    }

    path = this.root.resolve(PROJECT_PREFIX + profileName + ".properties");
    if (Files.exists(path)) {
        located.add(path.toUri().toURL());
    }

    return located.stream();
}
 
Example 2
public static void main(String[] args) {
	// TODO Auto-generated method stub
	List<Student> students=new ArrayList<Student>();
	students.add(new Student("A",1,89));
	students.add(new Student("B",12,80));
	students.add(new Student("A1",10,67));
	students.add(new Student("C",7,56));
	students.add(new Student("A",5,90));
	
	Stream<Student> stream=students.stream();
	Consumer<Student> consumer=System.out::println;
	stream.forEach(consumer);
	
	System.out.println("******NAMES STARTING WITH A");
	Predicate<Student> predicate=student->student.getName().startsWith("A");
	students.stream().filter(predicate).forEach(consumer);
	
	System.out.println("******NAMES in  Lower cases");
	Function<Student,String>fun_to_lower=student->student.getName().toLowerCase();
	students.stream().map(fun_to_lower).forEach(System.out::println);

	
	System.out.println("******NAMES in  Lower cases");
	students.stream().map(Student::getName).filter(name->name.startsWith("A")).forEach(System.out::println);
	
}
 
Example 3
private static void useFlatMap3(List<Optional<Integer>> list){
    Function<Optional<Integer>, Stream<Optional<Integer>>> tryUntilWin = opt -> {
        List<Optional<Integer>> opts = new ArrayList<>();
        if(opt.isPresent()){
            opts.add(opt);
        } else {
            int prize = 0;
            while(prize == 0){
                double d = Math.random() - 0.8;
                prize = d > 0 ? (int)(1000000 * d) : 0;
                opts.add(Optional.of(prize));
            }
        }
        return opts.stream();
    };
    list.stream().flatMap(tryUntilWin).forEach(weWonOpt());
}
 
Example 4
Source Project: ethsigner   File: FileUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String readFirstLineFromFile(final Path file) throws IOException {
  final List<String> lines = Files.readAllLines(file);
  try (final Stream<String> linesStream = lines.stream()) {
    return linesStream
        .findFirst()
        .orElseThrow(() -> new InitializationException("Cannot read from empty file"));
  }
}
 
Example 5
Source Project: org.hl7.fhir.core   File: RoundTripTest.java    License: Apache License 2.0 5 votes vote down vote up
public static Stream<Arguments> getFiles() throws IOException {
 List<Arguments> params = new ArrayList();
 String examples = Utilities.path(root, "examples");
 for (File f : new File(examples).listFiles()) {
	 if (f.getName().endsWith(".xml")) {
		 params.add(Arguments.of(f));
	 }
 }
 return params.stream();
}
 
Example 6
Source Project: smart-testing   File: TagsParser.java    License: Apache License 2.0 5 votes vote down vote up
private Stream<String> retrieveTagFromAnnotation(Annotation tagsAnnotation) {
    final List<String> tags = new ArrayList<>();
    if (TAG.equals(tagsAnnotation.annotationType().getName())) {
        final String tagName = getTagName(tagsAnnotation);
        if (tagName != null) {
            tags.add(tagName);
        }
    } else {
        tags.addAll(getMultipleTagNames(tagsAnnotation));
    }
    return tags.stream();
}
 
Example 7
Source Project: vividus   File: MergingTableTransformer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String transform(String tableAsString, TableParsers tableParsers, TableProperties properties)
{
    MergeMode mergeMode = getMandatoryEnumProperty(properties, "mergeMode", MergeMode.class);

    List<String> tables = Optional.ofNullable(properties.getProperties().getProperty("tables"))
            .stream()
            .map(t -> t.split("(?<!\\\\);"))
            .flatMap(Stream::of)
            .map(t -> t.replace("\\;", ";").trim())
            .distinct()
            .filter(not(String::isBlank))
            .collect(Collectors.toList());

    Stream<String> examplesTablesStream = tables.stream();
    if (tableAsString.isBlank())
    {
        isTrue(tables.size() > 1, "Please, specify more than one unique table paths");
    }
    else
    {
        isTrue(!tables.isEmpty(), "Please, specify at least one table path");
        examplesTablesStream = Stream.concat(examplesTablesStream, Stream.of(tableAsString));
    }

    List<ExamplesTable> examplesTables = examplesTablesStream
            .map(p -> configuration.examplesTableFactory().createExamplesTable(p))
            .collect(Collectors.toCollection(LinkedList::new));
    String fillerValue = properties.getProperties().getProperty("fillerValue");
    return mergeMode.merge(examplesTables, properties, Optional.ofNullable(fillerValue));
}
 
Example 8
Source Project: tutorials   File: UserRepositoryCustomImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
    List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
    Stream<User> allUsersStream = allUsers.stream();
    for (java.util.function.Predicate<User> predicate : predicates) {
        allUsersStream = allUsersStream.filter(predicate);
    }

    return allUsersStream.collect(Collectors.toList());
}
 
Example 9
private static Stream<Arguments> data() {
	List<Arguments> args = new ArrayList<>();

	for (DigestAlgorithm digestAlgo : DigestAlgorithm.values()) {
		SignatureAlgorithm sa = SignatureAlgorithm.getAlgorithm(EncryptionAlgorithm.ECDSA, digestAlgo);
		if (sa != null && Utils.isStringNotBlank(sa.getOid())) {
			for (DigestAlgorithm messageDigest : DigestAlgorithm.values()) {
				if (!isShake(messageDigest)) {
					args.add(Arguments.of(digestAlgo, messageDigest));
				}
			}
		}
	}
	return args.stream();
}
 
Example 10
@Test
public void shouldStreamCollectionStreamToJSON() throws Exception {
    DummyObject dummyObject1 = new DummyObject("demoKey1", "demoValue1");
    DummyObject dummyObject2 = new DummyObject("demoKey2", "demoValue2");
    List<DummyObject> dummyCollection = Arrays.asList(dummyObject1, dummyObject2);
    collection2InputStream = new Stream2JSONInputStream(dummyCollection.stream());

    assertThat(inputStreamToString(collection2InputStream), is(GSON.toJson(dummyCollection)));
}
 
Example 11
@Override
Stream<String> implList() throws IOException {
    // take snapshot to avoid async close
    List<String> names = jf.stream()
            .filter(e -> e.section() == JmodFile.Section.CLASSES)
            .map(JmodFile.Entry::name)
            .collect(Collectors.toList());
    return names.stream();
}
 
Example 12
public static Stream<Arguments> data() throws FileNotFoundException, IOException {
  String src = TextFile.fileToString(TestingUtilities.resourceNameToFile("graphql", "parser-tests.gql"));
  String[] tests = src.split("###");
  List<Arguments> objects = new ArrayList<>();
  for (String s : tests) {
    if (!Utilities.noString(s.trim())) {
      int l = s.indexOf('\r');
      objects.add(Arguments.of(s.substring(0, l), s.substring(l + 2).trim()));
    }
  }
  return objects.stream();
}
 
Example 13
Source Project: epcis   File: ExternalTraversalEngine.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add a RandomFilterPipe to the end of the Pipeline. A biased coin toss
 * determines if the object is emitted or not.
 *
 * random number: 0~1 ( higher -> less filtered )
 *
 * Path Enabled: Greedy
 * 
 * Path Disabled: Lazy
 * 
 * Pipeline: Stream -> Filtered Stream
 * 
 * Path: Map<DeduplicationHolder, Filtered Set<Object>>
 * 
 * @param bias:
 *            pass if bias > random the bias of the random coin
 * @return the extended Pipeline
 */
public ExternalTraversalEngine random(final Double bias) {
	// Pipeline Update
	if (isPathEnabled) {
		List intermediate = (List) stream.filter(e -> bias > new Random().nextDouble())
				.collect(Collectors.toList());

		// Update Path ( Filter if any last elements of each path are not
		// included in intermediate )
		currentPath.keySet().retainAll(intermediate);

		// Make stream again
		if (isParallel)
			stream = intermediate.parallelStream();
		else
			stream = intermediate.stream();

	} else {
		stream = stream.filter(e -> bias > new Random().nextDouble());
	}

	// Step Update
	final Class[] args = new Class[1];
	args[0] = Double.class;
	final Step step = new Step(this.getClass().getName(), "random", args, bias);
	stepList.add(step);
	return this;
}
 
Example 14
private static Stream<Arguments> data() {
	List<DigestAlgorithm> digestAlgos = Arrays.asList(DigestAlgorithm.SHA1, DigestAlgorithm.SHA224,
			DigestAlgorithm.SHA256, DigestAlgorithm.SHA384, DigestAlgorithm.SHA512,
			DigestAlgorithm.SHA3_224, DigestAlgorithm.SHA3_256, DigestAlgorithm.SHA3_384, DigestAlgorithm.SHA3_512
	);

	List<Arguments> args = new ArrayList<>();
	for (DigestAlgorithm digest1 : digestAlgos) {
		for (DigestAlgorithm digest2 : digestAlgos) {
			args.add(Arguments.of(digest1, digest2));
		}
	}
	return args.stream();
}
 
Example 15
Source Project: tutorials   File: UserRepositoryCustomImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
    List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
    Stream<User> allUsersStream = allUsers.stream();
    for (java.util.function.Predicate<User> predicate : predicates) {
        allUsersStream = allUsersStream.filter(predicate);
    }

    return allUsersStream.collect(Collectors.toList());
}
 
Example 16
private Function<AssociationDescriptor, Stream<EntityReference>> manyAssociationFunction(
    ModuleDescriptor module, Map<String, Value> namedValues )
{
    return association ->
    {
        List list = doDeserialize( module, ENTITY_REF_LIST_VALUE_TYPE,
                                   namedValues.get( association.qualifiedName().name() ) );
        return list == null ? Stream.empty() : list.stream();
    };
}
 
Example 17
Source Project: KOMORAN   File: DicUserStreamParser.java    License: Apache License 2.0 5 votes vote down vote up
public static Stream<DicUser> parse(String input) {
    String[] elements = input.split("\t");
    List<DicUser> resultItems = new ArrayList<>();
    DicUser anItem = new DicUser();
    String token;
    PosType pos;

    // TOKEN ONLY
    if (elements.length < 2) {
        token = input.trim();
        pos = PosType.valueOf("NNP");
    }
    // TOKEN & POS
    else if (elements.length == 2) {
        token = elements[0];
        String posInRaw = elements[1];

        try {
            pos = PosType.valueOf(posInRaw.toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new ResourceMalformedException("잘못된 품사, " + input);
        }
    } else {
        throw new ResourceMalformedException("잘못된 입력, " + input);
    }

    anItem.setToken(token);
    anItem.setPos(pos);

    resultItems.add(anItem);

    return resultItems.stream();
}
 
Example 18
Source Project: code   File: TestStreamAPI2.java    License: Apache License 2.0 5 votes vote down vote up
public static Stream<Character> filterCharacter(String str) {
    List<Character> list = new ArrayList<>();
    for (Character ch : str.toCharArray()) {
        list.add(ch);
    }
    return list.stream();
}
 
Example 19
private Stream<MethodSpec> operations(OperationModel opModel) {
    List<MethodSpec> methods = new ArrayList<>();
    methods.add(traditionalMethod(opModel));
    if (opModel.isPaginated()) {
        methods.add(paginatedTraditionalMethod(opModel));
    }
    return methods.stream();
}
 
Example 20
public static <T> Stream<T> fromList( List<T> list ) {
    return list.stream();
}