java.util.List#stream ( )源码实例Demo

下面列出了java.util.List#stream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: thorntail   文件: FilesystemConfigLocator.java
@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();
}
 
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);
	
}
 
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());
}
 
源代码4 项目: ethsigner   文件: FileUtil.java
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"));
  }
}
 
源代码5 项目: org.hl7.fhir.core   文件: RoundTripTest.java
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();
}
 
源代码6 项目: smart-testing   文件: TagsParser.java
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();
}
 
源代码7 项目: vividus   文件: MergingTableTransformer.java
@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));
}
 
源代码8 项目: tutorials   文件: UserRepositoryCustomImpl.java
@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());
}
 
源代码9 项目: dss   文件: CAdESLevelBWithECDSATest.java
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();
}
 
源代码10 项目: smarthome   文件: Stream2JSONInputStreamTest.java
@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)));
}
 
源代码11 项目: openjdk-jdk9   文件: ModuleReferences.java
@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();
}
 
源代码12 项目: org.hl7.fhir.core   文件: GraphQLParserTests.java
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();
}
 
源代码13 项目: epcis   文件: ExternalTraversalEngine.java
/**
 * 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;
}
 
源代码14 项目: dss   文件: CAdESLevelBNONEWithECDSATest.java
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();
}
 
源代码15 项目: tutorials   文件: UserRepositoryCustomImpl.java
@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());
}
 
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();
    };
}
 
源代码17 项目: KOMORAN   文件: DicUserStreamParser.java
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();
}
 
源代码18 项目: code   文件: TestStreamAPI2.java
public static Stream<Character> filterCharacter(String str) {
    List<Character> list = new ArrayList<>();
    for (Character ch : str.toCharArray()) {
        list.add(ch);
    }
    return list.stream();
}
 
源代码19 项目: aws-sdk-java-v2   文件: AsyncClientInterface.java
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();
}
 
源代码20 项目: hortonmachine   文件: StreamUtils.java
public static <T> Stream<T> fromList( List<T> list ) {
    return list.stream();
}