one.util.streamex.StreamEx Java Examples

The following examples show how to use one.util.streamex.StreamEx. 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 check out the related API usage on the sidebar.
Example #1
Source File: ArrangeDisplayViews.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static void process(final MElementContainer uiRoot, final GamaNode<String> treeRoot,
		final List<MPlaceholder> holders) {
	final String data = treeRoot.getData();
	final String weight = String.valueOf(treeRoot.getWeight());
	// DEBUG.OUT("Processing " + data + " with weight " + weight);
	final Boolean dir = !data.equals(HORIZONTAL) && !data.equals(VERTICAL) ? null : data.equals(HORIZONTAL);
	final MPlaceholder holder = StreamEx.of(holders)
			.findFirst(h -> h.getTransientData().get(DISPLAY_INDEX_KEY).equals(data)).orElse(null);
	final MElementContainer container = create(uiRoot, weight, dir);
	if (holder != null) {
		if (container.equals(uiRoot)) {
			holder.setContainerData(weight);
		}
		container.getChildren().add(holder);
	} else {
		for (final GamaNode<String> node : treeRoot.getChildren()) {
			process(container, node, holders);
		}
	}
}
 
Example #2
Source File: ContainerBuilderStubIndex.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, ContainerBuilderCall, FileContent> getIndexer() {

    return inputData -> {

        Map<String, ContainerBuilderCall> map = new THashMap<>();

        PsiFile psiFile = inputData.getPsiFile();
        if(!(psiFile instanceof PhpFile) ||
            !Symfony2ProjectComponent.isEnabledForIndex(psiFile.getProject()) ||
            !isValidForIndex(inputData, psiFile)
            ){

            return map;
        }

        StreamEx.of(PhpPsiUtil.findAllClasses((PhpFile) psiFile))
            .flatMap(clazz -> StreamEx.of(clazz.getOwnMethods()))
            .forEach(method -> processMethod(method, map));
        return map;
    };
}
 
Example #3
Source File: PhpHighlightPackParametersUsagesHandlerFactory.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
@Override
public @Nullable HighlightUsagesHandlerBase createHighlightUsagesHandler(@NotNull Editor editor, @NotNull PsiFile file, @NotNull PsiElement target) {

    ParameterList parameterList = PhpPsiUtil.getParentByCondition(target, true, ParameterList.INSTANCEOF, Statement.INSTANCEOF);
    if (parameterList == null) {
        return null;
    }

    FunctionReference functionCall = ObjectUtils.tryCast(parameterList.getParent(), FunctionReference.class);
    String fqn = resolveFqn(functionCall);
    if (!"\\pack".equals(fqn)) {
        return null;
    }

    PsiElement[] parameters = parameterList.getParameters();
    PsiElement selectedParameter = StreamEx.of(parameters).findFirst((p) -> p.getTextRange().containsOffset(editor.getCaretModel().getOffset())).orElse(null);
    if (selectedParameter == null) {
        return null;
    }

    int selectedIndex = PhpCodeInsightUtil.getParameterIndex(selectedParameter);
    if (selectedIndex < 0 || selectedIndex >= parameters.length) {
        return null;
    }
    return new PhpHighlightPackParametersUsagesHandler(editor, file, 0, selectedIndex, parameters);
}
 
Example #4
Source File: Containers.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@operator (
		value = { "index_by" },
		iterator = true,
		content_type = ITypeProvider.CONTENT_TYPE_AT_INDEX + 1,
		index_type = ITypeProvider.TYPE_AT_INDEX + 2,
		category = IOperatorCategory.CONTAINER,
		concept = { IConcept.CONTAINER })
@doc (
		value = "produces a new map from the evaluation of the right-hand operand for each element of the left-hand operand",
		usages = {
				@usage ("if the left-hand operand is nil, index_by throws an error. If the operation results in duplicate keys, only the first value corresponding to the key is kept") },
		examples = { @example (
				value = "[1,2,3,4,5,6,7,8] index_by (each - 1)",
				equals = "[0::1, 1::2, 2::3, 3::4, 4::5, 5::6, 6::7, 7::8]") },
		see = {})
public static IMap index_by(final IScope scope, final IContainer original, final IExpression keyProvider) {

	final StreamEx s = original.stream(scope);
	final IType contentsType = original.getGamlType().getContentType();
	return (IMap) s.collect(Collectors.toMap(with(scope, keyProvider), (a) -> a, (a, b) -> a,
			asMapOf(keyProvider.getGamlType(), contentsType)));
}
 
Example #5
Source File: WrappedContainer.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public void initializeChildren() {
	if (!isOpen()) {
		children = EMPTY;
		return;
	}
	try {
		final IResource[] cc = getResource().members();
		final int size = cc.length;
		if (size == 0)
			children = EMPTY;
		else {
			children = StreamEx.of(cc).filter(r -> r.getName().charAt(0) != '.').map(r -> getManager().wrap(this, r))
					.toArray(WrappedResource.class);
		}
	} catch (final CoreException e) {
		e.printStackTrace();
	}
	countModels();
}
 
Example #6
Source File: HeadlessSimulationLoader.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Compiles a file to a GAMA model ready to be experimented
 *
 * @param myFile
 *            the main model file
 * @param errors
 *            a list that will be filled with compilation errors / warnings (can be null)
 * @param metaProperties
 *            an instance of GamlProperties that will be filled with the sylmbolic names of bundles required to run
 *            the model (can be null) and other informations (skills, operators, statements, ...).
 * @return a compiled model
 * @throws IOException
 *             in case the file is null or not found
 * @throws GamaHeadlessException
 *             in case the compilation ends in error
 */
public static synchronized IModel loadModel(final File myFile, final List<GamlCompilationError> errors,
		final GamlProperties metaProperties) throws IOException, GamaHeadlessException {
	if (myFile == null) { throw new IOException("Model file is null"); }
	final String fileName = myFile.getAbsolutePath();
	if (!myFile.exists()) { throw new IOException("Model file does not exist: " + fileName); }
	DEBUG.LOG(fileName + " model is being compiled...");

	final IModel model = GamlModelBuilder.getDefaultInstance().compile(URI.createFileURI(fileName), errors);
	if (model == null) {
		DEBUG.LOG("Model compiled with following indications: \n"
				+ (errors == null ? "" : StreamEx.of(errors).joining("\n")));
		throw new GamaHeadlessException(
				"Model cannot be compiled. See list of attached errors \n" + StreamEx.of(errors).joining("\n"));
	}
	// if (metaProperties != null)
	// model.getDescription().collectMetaInformation(metaProperties);
	return model;
}
 
Example #7
Source File: ContainerBuilderStubIndex.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void processMethod(@NotNull Method method, @NotNull Map<String, ContainerBuilderCall> map) {
    Set<CharSequence> containerParameters = StreamEx.of(method.getParameters())
        .filter(ContainerBuilderStubIndex::isContainerParam)
        .map(Parameter::getNameCS)
        .toSet();
    if (containerParameters.isEmpty()) return;
    MyInstructionProcessor processor = new MyInstructionProcessor(map, containerParameters);
    for (PhpInstruction instruction : method.getControlFlow().getInstructions()) {
        instruction.process(processor);
    }
}
 
Example #8
Source File: AbstractSummary.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public AbstractSummary<?> getSummaryOf(final URI uri) {
	// if (this.uri != null) {
	// DEBUG.OUT("Comparing " + this.uri + " to " + uri);
	// }
	if (uri.equals(this.uri)) { return this; }
	return StreamEx.ofValues(getSummaries()).findFirst(s -> s.getSummaryOf(uri) != null).orElse(null);
}
 
Example #9
Source File: BaseCodeServiceImpl.java    From dynamic-data-source-demo with Apache License 2.0 5 votes vote down vote up
@Override
public List<BaseCode> getListClassifyByCity(EnumBaseCode type, Integer officeAddress) {
    BaseCode param = BaseCode.builder()
            .codeType(type.getCode())
            .build();
    List<BaseCode> all = baseCodeMapper.select(param);
    // 将查询结果按照 parent-code 分组
    Map<String, List<BaseCode>> map = StreamEx.of(all).groupingBy(BaseCode::getParentCode);
    // 获取一级 base-code
    List<BaseCode> parents = map.get("0");
    // 遍历一级 base-code 并将其对应的二级 base-code 设置进去
    parents.forEach(parent -> parent.setSubList(map.get(parent.getCode())));
    return checkList(parents, officeAddress);
}
 
Example #10
Source File: BaseCodeServiceImpl.java    From dynamic-data-source-demo with Apache License 2.0 5 votes vote down vote up
private static List<BaseCode> checkList(List<BaseCode> all, Integer officeAddress) {
    if (isEmpty(all)) {
        return emptyList();
    }
    // 将查询结果按照 office-address 分组,office-address 不能为 null,默认值为 0
    Map<Integer, List<BaseCode>> map = StreamEx.of(all).groupingBy(BaseCode::getOfficeAddress);
    // 查找当前 office-address 的 value,若没有,则返回默认值,0 为默认值,若没有默认值则返回 Optional.empty()
    return map.containsKey(officeAddress) ? map.get(officeAddress) : map.get(0);
}
 
Example #11
Source File: JsonReader.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public StreamEx<T> read() {
    var gson = new Gson();
    try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
         var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
        return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
            Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
            Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
        ));
    } catch (IOException ex) {
        throw new IllegalArgumentException(
            format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
    }
}
 
Example #12
Source File: ReadTest.java    From dynamic-data-source-demo with Apache License 2.0 5 votes vote down vote up
@Test
public void multi() {
    DynamicDataSourceHolder.routeMaster();
    List<BaseCode> master = baseCodeService.getListByCity(DROP_REASON, 0);
    StreamEx.of(master).map(gson::toJson).forEach(log::info);
    DynamicDataSourceHolder.routeSlave();
    List<BaseCode> slave = baseCodeService.getListByCity(DROP_REASON, 0);
    StreamEx.of(slave).map(gson::toJson).forEach(log::info);
}
 
Example #13
Source File: YamlReader.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
public StreamEx<T> read() {
    try {
        var yamlFactory = new YAMLFactory();
        return StreamEx.of(new ObjectMapper(yamlFactory)
            .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
            .readValues(yamlFactory.createParser(getUrl()), entityClass)
            .readAll());
    } catch (Exception ex) {
        throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
    }
}
 
Example #14
Source File: CsvReader.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@Override
public StreamEx<T> read() {
    try (var csvParser = parse(getUrl(), StandardCharsets.UTF_8,
            CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim())) {
        var entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
        return StreamEx.of(csvParser.getRecords())
                .map(record -> StreamEx.of(entityFields).map(record::get).toArray())
                .map(args -> onClass(entityClass).create(args).get());
    } catch (IOException ex) {
        throw new IllegalArgumentException(
                format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
    }
}
 
Example #15
Source File: PhpHighlightPackParametersUsagesHandler.java    From idea-php-advanced-autocomplete with MIT License 5 votes vote down vote up
@NotNull
private static List<StringLiteralExpression> getLiteralExpressions(BinaryExpression parameter, Editor editor) {
    List<PsiElement> parts = ContainerUtil.map(PhpConcatenationStringRepresentationConverter.INSTANCE.getStringParts(parameter, editor), PhpStringPartDescriptor::getElement);
    List<StringLiteralExpression> expressions = StreamEx.of(parts).select(StringLiteralExpression.class).collect(Collectors.toList());
    boolean allExpressionHaveSameQuotes = ((StreamEx)StreamEx.of(expressions).distinct(StringLiteralExpression::isSingleQuote)).limit(2L).count() <= 1L;

    return expressions.size() == parts.size() && allExpressionHaveSameQuotes ? expressions : Collections.emptyList();
}
 
Example #16
Source File: CollectionsDataSupplierTests.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@DataSupplier(transpose = true)
public Set<User> extractCustomListData() {
    return StreamEx.of(
        new User("username", "password"),
        new User("username", "password"),
        null,
        null).toSet();
}
 
Example #17
Source File: StreamsDataSupplierTests.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@DataSupplier
public StreamEx<String> getCustomStreamData() {
    return StreamEx.of(
        new User("user2", "password2"),
        new User("user3", "password3"),
        new User("user1", "password1"))
        .map(User::getName)
        .sorted()
        .skip(1);
}
 
Example #18
Source File: InvokedMethodNameListener.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeInvocation(final IInvokedMethod method, final ITestResult testResult) {
    if (method.isTestMethod()) {
        final String rawMethodName = method.getTestMethod().getMethodName();
        final long currentThreadId = Thread.currentThread().getId();

        threads.putIfAbsent(rawMethodName, new CopyOnWriteArrayList<>());
        threads.computeIfPresent(rawMethodName,
            (s, l) -> StreamEx.of(l).append(currentThreadId).distinct().toList());

        invokedMethodNames.add(getName(testResult));
    }
}
 
Example #19
Source File: JsonDataSupplierTests.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@DataSupplier
public StreamEx<Animal> getAnimals() {
    return use(JsonReader.class)
        .withTarget(Animal.class)
        .withSource("https://raw.githubusercontent.com/LearnWebCode/json-example/master/animals-1.json")
        .read();
}
 
Example #20
Source File: TupleDataSupplierTests.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@DataSupplier(flatMap = true)
public StreamEx getInternallyExtractedTupleData() {
    var list1 = asList("data1", "data2");
    var list2 = asList("data3", "data4", "data5");
    var minSize = Math.min(list1.size(), list2.size());

    return EntryStream.of(list1)
        .limit(minSize)
        .mapKeyValue((i, val) -> Tuple.of(val, list2.get(i)));
}
 
Example #21
Source File: CsvDataSupplierTests.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@DataSupplier
public StreamEx<User> getUsers() {
    return use(CsvReader.class)
        .withTarget(User.class)
        .withSource("users.csv")
        .read();
}
 
Example #22
Source File: StreamExMergeStreamsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
    Stream<Integer> stream1 = Stream.of(1, 3, 5);
    Stream<Integer> stream2 = Stream.of(2, 4, 6);

    Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2);

    assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
}
 
Example #23
Source File: StackUtils.java    From healenium-web with Apache License 2.0 5 votes vote down vote up
private List<StackTraceElement> normalize(StackTraceElement[] traceElements){
    List<StackTraceElement> elementList = Arrays.stream(traceElements)
            .filter(redundantPackages())
            .collect(Collectors.toList());
    Collections.reverse(elementList);
    elementList = StreamEx.of(elementList)
            .takeWhile(it-> !it.getClassName().equals(BaseHandler.class.getName()))
            .toList();
    return elementList.subList(0, elementList.size() -1);
}
 
Example #24
Source File: DockerComposeRuleConfig.java    From docker-compose-rule with Apache License 2.0 5 votes vote down vote up
private static StreamEx<File> dirAndParents(File startDir) {
    return StreamEx.of(Stream.generate(new Supplier<Optional<File>>() {
        private Optional<File> dir = Optional.of(startDir.getAbsoluteFile());

        @Override
        public Optional<File> get() {
            Optional<File> toReturn = dir;
            dir = dir.flatMap(directory -> Optional.ofNullable(directory.getParentFile()));
            return toReturn;
        }
    }))
            .takeWhile(Optional::isPresent)
            .map(Optional::get);
}
 
Example #25
Source File: BlazeGoPackage.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public StreamEx<PsiDirectory> getPsiDirectories() {
  PsiManager psiManager = PsiManager.getInstance(getProject());
  return StreamEx.of(getDirectories())
      .map(psiManager::findDirectory)
      .filter(Objects::nonNull)
      .filter(PsiDirectory::isValid);
}
 
Example #26
Source File: StreamEX.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    // Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
    List<User> users = Arrays.asList(new User("name"), new User(), new User());
    users.stream().map(User::getName).collect(Collectors.toList());
    List<String> userNames = StreamEx.of(users).map(User::getName).toList();
    Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole);
    StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
    // Selecting stream elements of specific type
    List usersAndRoles = Arrays.asList(new User(), new Role());
    List<Role> roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList();
    System.out.println(roles);
    // adding elements to Stream
    List<String> appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList();
    System.out.println(appendedUsers);
    // Removing unwanted elements and using the stream as Iterable:
    for (String line : StreamEx.of(users).map(User::getName).nonNull()) {
        System.out.println(line);
    }
    // Selecting map keys by value predicate:
    Map<String, Role> nameToRole = new HashMap<>();
    nameToRole.put("first", new Role());
    nameToRole.put("second", null);
    Set<String> nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet();
    System.out.println(nonNullRoles);
    // Operating on key-value pairs:
    Map<User, List<Role>> users2roles = transformMap(role2users);
    Map<String, String> mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap();
    // Support of byte/char/short/float types:
    short[] src = { 1, 2, 3 };
    char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray();
}
 
Example #27
Source File: PlatformAgent.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings ("unchecked")
@getter (
		value = "plugins",
		initializer = true)
public IList<String> getPluginsList() {
	final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
	return StreamEx.of(bc.getBundles()).map(b -> b.getSymbolicName()).toCollection(Containers.listOf(Types.STRING));
}
 
Example #28
Source File: StreamExMergeStreamsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
    Stream<String> stream1 = Stream.of("foo", "bar");
    Stream<String> openingBracketStream = Stream.of("[");
    Stream<String> closingBracketStream = Stream.of("]");

    Stream<String> resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream);

    assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
}
 
Example #29
Source File: ISpecies.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings ("unchecked")
@getter (SUBSPECIES)
@doc ("Returns all the direct subspecies names of this species")
default IList<String> getSubSpeciesNames(final IScope scope) {
	return StreamEx.of(getSubSpecies(scope)).map((each) -> each.getName())
			.toCollection(Containers.listOf(Types.STRING));
}
 
Example #30
Source File: PhpHighlightPackParametersUsagesHandler.java    From idea-php-advanced-autocomplete with MIT License 5 votes vote down vote up
private int resolveSpecificationIndexFromCaret(@NotNull HashMap<Integer, RelativeRange> specificationRelativeRanges) {
    int caretOffset = this.myEditor.getCaretModel().getOffset();
    StringLiteralExpression selectedLiteralExpression = PhpPsiUtil.getParentByCondition(this.myFile.findElementAt(caretOffset), false, StringLiteralExpression.INSTANCEOF);
    return StreamEx.of(specificationRelativeRanges.entrySet())
        .findFirst((e) -> specificationAtCaretOffsetExists(caretOffset, selectedLiteralExpression, e.getValue()))
        .map(Map.Entry::getKey).orElse(-1);
}