当前位置: 首页>>代码示例>>Java>>正文


Java Collectors类代码示例

本文整理汇总了Java中java.util.stream.Collectors的典型用法代码示例。如果您正苦于以下问题:Java Collectors类的具体用法?Java Collectors怎么用?Java Collectors使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Collectors类属于java.util.stream包,在下文中一共展示了Collectors类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getStudyplanDetailsView

import java.util.stream.Collectors; //导入依赖的package包/类
@GetMapping(params = "id")
private String getStudyplanDetailsView(@RequestParam(value = "id") Long id, Model model) {
    StudyPlan studyPlan = studyPlanService.findOne(id);

    List<SubjectForStudyPlan> subjectsForStudyPlan = studyPlanService.getSubjectsForStudyPlan(id);
    List<SubjectForStudyPlan> mandatory = subjectsForStudyPlan
            .stream()
            .filter(SubjectForStudyPlan::getMandatory)
            .collect(Collectors.toList());
    List<SubjectForStudyPlan> optional = subjectsForStudyPlan
            .stream()
            .filter(s -> !s.getMandatory())
            .collect(Collectors.toList());

    model.addAttribute("studyPlan", studyPlan);
    model.addAttribute("mandatory", mandatory);
    model.addAttribute("optional", optional);

    return "student/all-studyplan-details";
}
 
开发者ID:university-information-system,项目名称:uis,代码行数:21,代码来源:StudentAllStudyPlansController.java

示例2: hostsRuntime

import java.util.stream.Collectors; //导入依赖的package包/类
public Map<String, ObjectNode> hostsRuntime ( List<String> hosts ) {

		return hosts.stream()
			.map( host -> {
				ObjectNode hostRuntime = hostResponseMap.get( host );
				if ( hostRuntime == null ) {
					hostRuntime = jsonMapper.createObjectNode();
					hostRuntime.put( "error", "No response found" );
				}
				hostRuntime.put( "collectedHost", host );
				return hostRuntime;
			} )
			.collect( Collectors.toMap(
				hostStatus -> hostStatus.get( "collectedHost" ).asText(),
				hostStatus -> hostStatus ) );
	}
 
开发者ID:csap-platform,项目名称:csap-core,代码行数:17,代码来源:HostStatusManager.java

示例3: generateSource

import java.util.stream.Collectors; //导入依赖的package包/类
/**
 * Generates source which represents the class.
 *
 * @return source which represents the class
 */
@Override
public String generateSource() {
    String sourceForAnnotations = generateSourceForAnnotations();
    String classModifiers = mods.stream().collect(Collectors.joining(" "));
    return sourceForAnnotations
            + String.format("%s%s %s %s %s {%n",
            indention(),
            classModifiers,
            classType.getDescription(),
            name,
            parent == null ? "" : "extends " + parent)
            + classType.collectFields(fields.values())
            + classType.collectMethods(methods.values())
            + classType.collectInnerClasses(innerClasses.values())
            + indention() + "}";
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:TestCase.java

示例4: fixUnitChanges

import java.util.stream.Collectors; //导入依赖的package包/类
private void fixUnitChanges() {
    // Unlike roles, we can not trust what is already there, as the changes
    // are deeper.

    if (compareVersion("0.116") > 0) return;

    unitChangeTypeList.clear();
    File uctf = FreeColDirectories.getCompatibilityFile(UNIT_CHANGE_TYPES_COMPAT_FILE_NAME);
    try (
         FileInputStream fis = new FileInputStream(uctf);
         ) {
        load(fis);
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to load unit changes.", e);
        return;
    }

    logger.info("Loading unit-changes backward compatibility fragment: "
        + UNIT_CHANGE_TYPES_COMPAT_FILE_NAME + " with changes: "
        + transform(getUnitChangeTypeList(), alwaysTrue(),
            UnitChangeType::getId, Collectors.joining(" ")));
}
 
开发者ID:wintertime,项目名称:FreeCol,代码行数:23,代码来源:Specification.java

示例5: test

import java.util.stream.Collectors; //导入依赖的package包/类
private void test(List<Integer> values, List<Double> probabilities) {
    final Map<Integer, AtomicInteger> results = new ConcurrentHashMap<>(
            values.stream()
                    .map(integer -> new AbstractMap.SimpleImmutableEntry<>(integer, new AtomicInteger(0)))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
    );

    IntStream.range(0, N)
            .parallel()
            .forEach(i -> {
                results.get(GenerateNonuniformRandomNumbers.getRandom(values,probabilities)).incrementAndGet();
            });

    IntStream.range(0, values.size())
            .parallel()
            .forEach(i -> {
                double expectedValue = N * probabilities.get(i);
                assertThat(results.get(values.get(i)), allOf(greaterThan(expectedValue - 50), lessThan(expectedValue + 50)));
            });
}
 
开发者ID:gardncl,项目名称:elements-of-programming-interviews,代码行数:21,代码来源:GenerateNonuniformRandomNumbersTest.java

示例6: getTable

import java.util.stream.Collectors; //导入依赖的package包/类
public static String getTable(Character[] borderChars, Column[] rawColumns, String[][] data) {
    if (borderChars.length != NO_BORDERS.length) {
        throw new IllegalArgumentException("Border characters array must be exactly " + NO_BORDERS.length + " elements long");
    }

    final int numColumns = getNumColumns(rawColumns, data);
    final Column[] columns = IntStream.range(0, numColumns)
            .mapToObj(index -> index < rawColumns.length ? rawColumns[index] : new Column())
            .toArray(Column[]::new);
    final int[] colWidths = getColWidths(columns, data);

    final HorizontalAlign[] headerAligns = Arrays.stream(columns).map(Column::getHeaderAlign).toArray(HorizontalAlign[]::new);
    final HorizontalAlign[] dataAligns = Arrays.stream(columns).map(Column::getDataAlign).toArray(HorizontalAlign[]::new);
    final HorizontalAlign[] footerAligns = Arrays.stream(columns).map(Column::getFooterAlign).toArray(HorizontalAlign[]::new);

    final String[] header = Arrays.stream(columns).map(Column::getHeader).toArray(String[]::new);
    final String[] footer = Arrays.stream(columns).map(Column::getFooter).toArray(String[]::new);

    List<String> tableRows = getTableRows(colWidths, headerAligns, dataAligns, footerAligns, borderChars, header, data, footer);

    return tableRows.stream()
            .filter(line -> !line.isEmpty())
            .collect(Collectors.joining(System.lineSeparator()));
}
 
开发者ID:freva,项目名称:ascii-table,代码行数:25,代码来源:AsciiTable.java

示例7: main

import java.util.stream.Collectors; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        test("p1", "read", "write", "delete", "execute");
        test("p2", "read,write", "delete,execute");
        test("p3", "read,write,delete", "execute");
        test("p4", "read,write,delete,execute");
    } else {
        SecurityManager sm = System.getSecurityManager();
        for (String arg : args) {
            // Use bits to create powerset of ALL_ACTIONS
            IntStream.range(1, 16)
                    .mapToObj(n -> IntStream.range(0, 4)
                            .filter(x -> (n & (1 << x)) != 0)
                            .mapToObj(x -> ALL_ACTIONS[x])
                            .collect(Collectors.joining(",")))
                    .forEach(a -> sm.checkPermission(
                            new FilePermission(arg, a)));
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:MergeName.java

示例8: testConst_enum

import java.util.stream.Collectors; //导入依赖的package包/类
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testConst_enum() {
	sqlContextFactory.setEnumConstantPackageNames(Arrays.asList(TestEnum1.class.getPackage().getName()));

	sqlContextFactory.initialize();

	Map<String, Parameter> constParameterMap = sqlContextFactory.getConstParameterMap();
	Set<String> set = constParameterMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue().getValue())
			.collect(Collectors.toSet());

	assertThat(
			set,
			is(new HashSet<>(Arrays.asList("CLS_TEST_ENUM1_A=A", "CLS_TEST_ENUM1_B=B", "CLS_TEST_ENUM1_C=C",
					"CLS_PACKTEST_TEST_ENUM2_D=D", "CLS_PACKTEST_TEST_ENUM2_E=E", "CLS_PACKTEST_TEST_ENUM2_F=F",
					"CLS_PACKTEST_TEST_ENUM2_INNER_G=G", "CLS_PACKTEST_TEST_ENUM2_INNER_H=H",
					"CLS_PACKTEST_TEST_ENUM2_INNER_I=I"))));

	for (Parameter parameter : constParameterMap.values()) {
		assertThat(parameter.getValue(), isA((Class) Enum.class));
	}
}
 
开发者ID:future-architect,项目名称:uroborosql,代码行数:23,代码来源:SqlContextFactoryTest.java

示例9: setAttribute

import java.util.stream.Collectors; //导入依赖的package包/类
/**
 * Retrieves all roles of the current user based on direct roles set to the user, its groups and their parent groups.
 * Then it recursively expands all composite roles, and restricts according to the given predicate {@code restriction}.
 * If the current client sessions is restricted (i.e. no client found in active user session has full scope allowed),
 * the final list of roles is also restricted by the client scope. Finally, the list is mapped to the token into
 * a claim.
 */
protected void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession,
                                   Predicate<RoleModel> restriction, String prefix) {
    String rolePrefix = prefix == null ? "" : prefix;
    UserModel user = userSession.getUser();

    // get a set of all realm roles assigned to the user or its group
    Stream<RoleModel> clientUserRoles = getAllUserRolesStream(user).filter(restriction);

    boolean dontLimitScope = userSession.getAuthenticatedClientSessions().values().stream().anyMatch(cs -> cs.getClient().isFullScopeAllowed());
    if (! dontLimitScope) {
        Set<RoleModel> clientRoles = userSession.getAuthenticatedClientSessions().values().stream()
          .flatMap(cs -> cs.getClient().getScopeMappings().stream())
          .collect(Collectors.toSet());

        clientUserRoles = clientUserRoles.filter(clientRoles::contains);
    }

    Set<String> realmRoleNames = clientUserRoles
      .map(m -> rolePrefix + m.getName())
      .collect(Collectors.toSet());

    setPlainAttribute(attributes, mappingModel, realmRoleNames);
}
 
开发者ID:Doccrazy,项目名称:keycloak-protocol-cas,代码行数:31,代码来源:AbstractUserRoleMappingMapper.java

示例10: listUploadedFiles

import java.util.stream.Collectors; //导入依赖的package包/类
@GetMapping("/")
  public String listUploadedFiles(Model model) {

      try {
      	logger.info("Fetching all Files from S3");
	model.addAttribute("files", s3OperationService.getAllFiles()
	        .stream()
	        .collect(Collectors.toMap(f-> f, f -> {
	        	List<String> filesNFolders = new ArrayList<>();
	        	String[] folders = f.split("/");
	        	Arrays.asList(folders).forEach(filesNFolders::add);
	        	return filesNFolders;
	        })));
} catch(IOException e) {
	logger.error("Failed to Connect to AWS S3 - Please check your AWS Keys");
	e.printStackTrace();
}

      return "index";
  }
 
开发者ID:RawSanj,项目名称:aws-s3-file-system,代码行数:21,代码来源:IndexController.java

示例11: fictitiousSwitchTest

import java.util.stream.Collectors; //导入依赖的package包/类
@Test
public void fictitiousSwitchTest() {
    Set<String> switchIds = Sets.newHashSet("BD", "BL");

    Network network = FictitiousSwitchFactory.create();
    List<Boolean> expectedSwitchStates = getSwitchStates(network, switchIds);

    BranchTripping tripping = new BranchTripping("CJ", "C");

    Set<Switch> switchesToOpen = new HashSet<>();
    Set<Terminal> terminalsToDisconnect = new HashSet<>();
    tripping.traverse(network, null, switchesToOpen, terminalsToDisconnect);
    assertEquals(switchIds, switchesToOpen.stream().map(Switch::getId).collect(Collectors.toSet()));
    assertEquals(Collections.emptySet(), terminalsToDisconnect);

    tripping.modify(network, null);
    assertTrue(network.getSwitch("BD").isOpen());
    assertTrue(network.getSwitch("BL").isOpen());

    List<Boolean> switchStates = getSwitchStates(network, switchIds);
    assertEquals(expectedSwitchStates, switchStates);
}
 
开发者ID:powsybl,项目名称:powsybl-core,代码行数:23,代码来源:BranchTrippingTest.java

示例12: parseReleaseStatusFile

import java.util.stream.Collectors; //导入依赖的package包/类
private List<Album> parseReleaseStatusFile(List<Album> albums) {
    Map<String, List<Album>> albumMap = albums.stream()
            .filter(album -> !StringUtils.isEmpty(album.getStatus()))
            .collect(Collectors.groupingBy(Album::getStatus));

    //read file into stream, try-with-resources
    try (Stream<String> stream = Files.lines(Paths.get(albumStatusFilePath))) {
        Stream<String[]> rows = stream.map(strRow -> strRow.split(TAB_SYMBOL));
        rows.forEach(row -> {
            List<Album> albumList = albumMap.get(row[0]);
            if (albumList != null) {
                albumList.forEach(album -> album.setStatus(row[1]));
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    return albums;
}
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:21,代码来源:AlbumParser.java

示例13: write

import java.util.stream.Collectors; //导入依赖的package包/类
static void write(ClassWriter classWriter, TypeSpec.Builder builder) {
    Map<Element, List<EgItem<?>>> examplesByElement = classWriter.getItems().stream()
            .collect(Collectors.groupingBy(EgItem::getElement));

    for (Map.Entry<Element, List<EgItem<?>>> entry: examplesByElement.entrySet()) {
        Element el = entry.getKey();
        List<EgItem<?>> examples = entry.getValue();

        new PatternMatchWriter(el, filterAndConvert(PatternMatchExample.class, examples), classWriter, builder)
                .addTests();
        new FunctionMatchWriter(el, filterAndConvert(FunctionMatchExample.class, examples), classWriter, builder)
                .addTests();

        if (el instanceof ExecutableElement) {
            ExecutableElement exEl = (ExecutableElement) el;

            List<ReturnsExample> returnsExamples = filterAndConvert(ReturnsExample.class, examples);
            new EgWriter(exEl, returnsExamples, classWriter, builder)
                    .addTests();

            List<ExceptionExample> exceptionExamples = filterAndConvert(ExceptionExample.class, examples);
            new ExceptionWriter(exEl, exceptionExamples, classWriter, builder)
                    .addTests();
        }
    }
}
 
开发者ID:dleppik,项目名称:EgTest,代码行数:27,代码来源:TestWriter.java

示例14: applyDefault

import java.util.stream.Collectors; //导入依赖的package包/类
/**
 * @param input
 *            {@link TextInputControl} where set the default value
 */
public void applyDefault(final TextInputControl input)
{
    try
    {
        settingDefaultOn = input;
        final String defaultText = Stream.of(mask) //
                                         .map(m -> Character.toString(m.getDefault()))
                                         .collect(Collectors.joining());
        input.setText(defaultText);

        final int firstAllowedPosition = IntStream.range(0, mask.length)
                                                  .filter(i -> mask[i].isNavigable())
                                                  .findFirst()
                                                  .orElse(0);
        input.selectRange(firstAllowedPosition, firstAllowedPosition);
    }
    finally
    {
        settingDefaultOn = null;
    }
}
 
开发者ID:ben12,项目名称:infxnity,代码行数:26,代码来源:MaskTextFilter.java

示例15: pomStandard

import java.util.stream.Collectors; //导入依赖的package包/类
@Test
public void pomStandard() throws Exception {
    File pom = new File(resources.getBasedir("valid"), "pom.xml");
    assertNotNull(pom);
    assertTrue(pom.exists());

    JavaClassGeneratorMojo mojo = (JavaClassGeneratorMojo) mojoRule.lookupMojo("generate-sources", pom);
    assertNotNull(mojo);

    mojo.sourceDestination = testFolder.getRoot().getPath();
    mojo.execute();

    Path path = Paths.get(mojo.sourceDestination);

    List<Path> files = Files.find(path, 99, (p, bfa) -> bfa.isRegularFile()).collect(Collectors.toList());
    assertEquals("Greeter and Mortal Class", 2l, files.size());
}
 
开发者ID:web3j,项目名称:web3j-maven-plugin,代码行数:18,代码来源:JavaClassGeneratorITest.java


注:本文中的java.util.stream.Collectors类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。