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


Java Set.forEach方法代码示例

本文整理汇总了Java中java.util.Set.forEach方法的典型用法代码示例。如果您正苦于以下问题:Java Set.forEach方法的具体用法?Java Set.forEach怎么用?Java Set.forEach使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.Set的用法示例。


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

示例1: main

import java.util.Set; //导入方法依赖的package包/类
public static void main(String[] args) {
    KafkaConsumer<String, String> consumer = createConsumer();
    consumer.subscribe(Arrays.asList(TOPIC));

    boolean flag = true;


    while (true) {
        ConsumerRecords<String, String> records = consumer.poll(100);
        if (flag) {
            Set<TopicPartition> assignments = consumer.assignment();
            assignments.forEach(topicPartition ->
                    consumer.seek(
                            topicPartition,
                            90));
            flag = false;
        }


        for (ConsumerRecord<String, String> record : records)
            System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
    }


}
 
开发者ID:jeqo,项目名称:post-kafka-rewind-consumer-offset,代码行数:26,代码来源:KafkaConsumerFromOffset.java

示例2: heartbeat

import java.util.Set; //导入方法依赖的package包/类
private void heartbeat() {
    try {
        Set<ControllerNode> peers = allNodes.values()
                .stream()
                .filter(node -> !(node.id().equals(localNode.id())))
                .collect(Collectors.toSet());
        State state = nodeStates.get(localNode.id());
        byte[] hbMessagePayload = SERIALIZER.encode(new HeartbeatMessage(localNode, state));
        peers.forEach((node) -> {
            heartbeatToPeer(hbMessagePayload, node);
            State currentState = nodeStates.get(node.id());
            double phi = failureDetector.phi(node.id());
            if (phi >= phiFailureThreshold) {
                if (currentState.isActive()) {
                    updateState(node.id(), State.INACTIVE);
                }
            } else {
                if (currentState == State.INACTIVE) {
                    updateState(node.id(), State.ACTIVE);
                }
            }
        });
    } catch (Exception e) {
        log.debug("Failed to send heartbeat", e);
    }
}
 
开发者ID:shlee89,项目名称:athena,代码行数:27,代码来源:DistributedClusterStore.java

示例3: addTaggedPost

import java.util.Set; //导入方法依赖的package包/类
public void addTaggedPost(Post post, Set<Tag> tags) {
    List<Topic> topics = topicsService.getAll();
    double score = redditScore(post);

    tags.forEach(tag -> {
        // Add to hot post list of tag
        hotPosts.add(CACHE_HOT_TAG_POSTS + tag.getId(), post.getId(), score);

        // Add to hot post list of topic
        topics.forEach(topic -> {
            if (topic.getTags().contains(tag)) {
                hotPosts.add(CACHE_HOT_TOPIC_POSTS + topic.getId(), post.getId(), score);
            }
        });
    });
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:17,代码来源:HotPostService.java

示例4: createOWLOntology

import java.util.Set; //导入方法依赖的package包/类
private static OWLOntology createOWLOntology(String documentIRI, Set<DiagramShape> shapes) {
  try {
    if (!documentIRI.endsWith("/")) {
      documentIRI = documentIRI + "/";
    }
    final IRI defaultIRI = IRI.create(documentIRI);
    final OWLOntology ontology = manager.createOntology(new OWLOntologyID(Optional.of(defaultIRI), Optional.absent()));
    shapes.forEach(shape -> {
      if (shape instanceof UMLClass) {
        manager.addAxioms(ontology, getClassAxioms(defaultIRI, (UMLClass) shape));
      }
      if (shape instanceof Relationship) {
        manager.addAxioms(ontology, getRelationAxioms(defaultIRI, (Relationship) shape));
      }
    });
    return ontology;
  } catch (OWLOntologyCreationException e) {
    logger.error(e.getMessage(), e);
    return null;
  }

}
 
开发者ID:onprom,项目名称:onprom,代码行数:23,代码来源:OWLExporter.java

示例5: findUsersWithRolesAndPermissions

import java.util.Set; //导入方法依赖的package包/类
private Set<User> findUsersWithRolesAndPermissions(Set<Role> roles, Set<Permission> permissions) {
    Set<User> userWithRole = new HashSet<>();
    Set<User> userWithPermissionLevel = new HashSet<>();

    if(permissions.isEmpty() && roles.isEmpty())
        return new HashSet<>(userRepository.findAll());

    permissions.
        forEach(permission -> userWithPermissionLevel.addAll(permission.getUsers()));
    if (roles.isEmpty())
        return userWithPermissionLevel;
    else {
        roles.forEach(role -> userWithRole.addAll(role.getUsers()));
        return Sets.intersection(userWithPermissionLevel, userWithRole);
    }
}
 
开发者ID:tosinoni,项目名称:SECP,代码行数:17,代码来源:GroupController.java

示例6: deletePost

import java.util.Set; //导入方法依赖的package包/类
@Caching(evict = {
    @CacheEvict(value = CACHE_POST, key = "#post.id.toString()"),
    @CacheEvict(value = CACHE_COUNT_USER_TAG_POSTS, key = "#post.user.id.toString().concat('_tags_posts_count')", allEntries = true),
    @CacheEvict(value = TagService.CACHE_COUNT_USER, key = "#post.user.id.toString().concat('_posts_count')")
})
@Transactional
public void deletePost(Post post) {
    PostStatus status = post.getStatus();
    postRepository.delete(post.getId());

    if (status == PostStatus.PUBLIC) {
        Set<Tag> tags = tagRepository.findPostTags(post.getId());
        hotPostService.removeHotPost(post);
        hotPostService.removeTaggedPost(post, tags);
        newPostsService.remove(post.getId());
        newPostsService.removeTaggedPost(post.getId(), tags);
        countingService.decPublicPostsCount();
        tags.forEach(tagService::decreasePostCountByOne); // 标签文章统计需要减一
    }

    PostSearchService.deleteIndex(post.getId());
    countingService.decPostsCount();
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:24,代码来源:PostService.java

示例7: getActiveTopicMap

import java.util.Set; //导入方法依赖的package包/类
@Override
public Map<String, List<String>> getActiveTopicMap() {
	Map<String, List<String>> topicGroupsMap = new HashMap<String, List<String>>();
	List<String> consumers = ZKUtils.getChildren(ZkUtils.ConsumersPath());
	for (String consumer : consumers) {
		Map<String, scala.collection.immutable.List<ConsumerThreadId>> consumer_consumerThreadId = null;
		try {
			consumer_consumerThreadId = JavaConversions
					.mapAsJavaMap(ZKUtils.getZKUtilsFromKafka().getConsumersPerTopic(consumer, true));
		} catch (Exception e) {
			LOG.warn("getActiveTopicMap-> getConsumersPerTopic for group: " + consumer + "failed! "
					+ e.getMessage());
			// TODO /consumers/{group}/ids/{id} 节点的内容不符合要求。这个group有问题
			continue;
		}
		Set<String> topics = consumer_consumerThreadId.keySet();
		topics.forEach(topic -> {
			List<String> _groups = null;
			if (topicGroupsMap.containsKey(topic)) {
				_groups = topicGroupsMap.get(topic);
				_groups.add(consumer);
			} else {
				_groups = new ArrayList<String>();
				_groups.add(consumer);
			}
			topicGroupsMap.put(topic, _groups);
		});
	}
	return topicGroupsMap;
}
 
开发者ID:chickling,项目名称:kmanager,代码行数:31,代码来源:ZKOffsetGetter.java

示例8: produceSubjectJson

import java.util.Set; //导入方法依赖的package包/类
private void produceSubjectJson(NetworkConfigService service, ObjectNode node,
                                Object subject,
                                boolean emptyIsError,
                                String emptyErrorMessage) {
    Set<? extends Config<Object>> configs = service.getConfigs(subject);
    if (emptyIsError) {
        // caller wants an empty set to be a 404
        configs = emptyIsNotFound(configs, emptyErrorMessage);
    }
    configs.forEach(c -> node.set(c.key(), c.node()));
}
 
开发者ID:shlee89,项目名称:athena,代码行数:12,代码来源:NetworkConfigWebResource.java

示例9: load

import java.util.Set; //导入方法依赖的package包/类
/**
 * Fills cache.
 *
 * @param switches {@link Set} of {@link SwitchInfoData} instances
 * @param isls     {@link Set} of {@link IslInfoData} instances
 */
public void load(Set<SwitchInfoData> switches, Set<IslInfoData> isls) {
    logger.debug("Switches: {}", switches);
    switches.forEach(this::createSwitch);

    logger.debug("Isls: {}", isls);
    isls.forEach(this::createIsl);
}
 
开发者ID:telstra,项目名称:open-kilda,代码行数:14,代码来源:NetworkCache.java

示例10: batchDownloadFile

import java.util.Set; //导入方法依赖的package包/类
/**
 * 批量下载文件
 *
 * @param fileUrls  文件路径集合
 * @param path      文件目录
 * @param threadNum 线程数
 */
public static void batchDownloadFile(Set<String> fileUrls, String path, int threadNum) {
    File destDir = new File(path);
    if (!destDir.isDirectory() || !destDir.exists()) {
        System.err.println("下载目录不存在");
        return;
    }
    threadNum = threadNum > 0 ? threadNum : DEFAULT_DOWNLOAD_THREAD_NUM;
    ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
    fileUrls.forEach((url -> {
        executorService.execute(() -> FileUtil.download(url, path));
    }));
    //TODO 等爬虫线程停止后再停止,或至少等待一段时间再停止
    executorService.shutdown();
}
 
开发者ID:java-webbee,项目名称:webBee,代码行数:22,代码来源:FileUtil.java

示例11: createWebsocketHandler

import java.util.Set; //导入方法依赖的package包/类
private void createWebsocketHandler(final HandlerCollection handlerCollection) {
    // https://github.com/jetty-project/embedded-jetty-websocket-examples/blob/master/javax.websocket-example/src/main/java/org/eclipse/jetty/demo/EventServer.java
    try {
        final Set<Class<?>> managedClasses = collectAnnotated(WEBSOCKET_MANAGED_CLASSES);
        final ServletContextHandler context = initContext("/websockets", managedClasses);
        handlerCollection.addHandler(context);
        final ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context);
        managedClasses.forEach(c -> registerEndpoint(wscontainer, c));
    } catch (final ServletException e) {
        throw new TestEEfiException("Failed to initialize websockets", e);
    }
}
 
开发者ID:dajudge,项目名称:testee.fi,代码行数:13,代码来源:RestServerImpl.java

示例12: testfindAuthByUserId

import java.util.Set; //导入方法依赖的package包/类
@Test
    @Transactional//no session
    public void  testfindAuthByUserId(){

        User user = userRepository.findOne(1L);
        Set<Role> roles = user.getRoles();
        Set<Authority> authoritySet = new HashSet<>(0);
        for (Role role : roles) {
            Set<Authority> authorities = role.getAuthorities();
            authoritySet.addAll(authorities);
        }

        //test:

        authoritySet.forEach(aur->{
            System.out.println("admin有权限:"+aur.getCode());
        });



//        for (Role role : roles) {
//            Set<Authority> authorities = role.getAuthorities();
//            for (Authority authority : authorities) {
//                System.out.println("admin有权限:"+authority.getName());
//                authoritySet.add(authority);
//            }
//        }

    }
 
开发者ID:mmdsyl,项目名称:BLOG-Microservice,代码行数:30,代码来源:InsertDataTest.java

示例13: setSuppressSubnet

import java.util.Set; //导入方法依赖的package包/类
/**
 * Sets names of ports to which SegmentRouting does not push subnet rules.
 *
 * @param suppressSubnet names of ports to which SegmentRouting does not push
 *                     subnet rules
 * @return this {@link SegmentRoutingAppConfig}
 */
public SegmentRoutingAppConfig setSuppressSubnet(Set<ConnectPoint> suppressSubnet) {
    if (suppressSubnet == null) {
        object.remove(SUPPRESS_SUBNET);
    } else {
        ArrayNode arrayNode = mapper.createArrayNode();
        suppressSubnet.forEach(connectPoint -> {
            arrayNode.add(connectPoint.deviceId() + "/" + connectPoint.port());
        });
        object.set(SUPPRESS_SUBNET, arrayNode);
    }
    return this;
}
 
开发者ID:shlee89,项目名称:athena,代码行数:20,代码来源:SegmentRoutingAppConfig.java

示例14: addRefs

import java.util.Set; //导入方法依赖的package包/类
private void addRefs(DataSetRefs refs, boolean isInput, String clusterName,
                                   Set<Tuple<String, String>> tableNames) {
    tableNames.forEach(tableName -> {
        final Referenceable ref = createTableRef(clusterName, tableName);
        if (isInput) {
            refs.addInput(ref);
        } else {
            refs.addOutput(ref);
        }
    });
}
 
开发者ID:bcgov,项目名称:nifi-atlas,代码行数:12,代码来源:Hive2JDBC.java

示例15: test1

import java.util.Set; //导入方法依赖的package包/类
@Test
public void test1() throws IOException, UnsupportedEncodingException {
    String testClassPath = System.getProperty("test.class.path", "");
    String deprcases = Stream.of(testClassPath.split(File.pathSeparator))
            .filter(e -> e.endsWith("cases"))
            .findAny()
            .orElseThrow(() -> new InternalError("cases not found"));
    boolean rval;

    System.out.println("test.src = " + System.getProperty("test.src"));
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ByteArrayOutputStream berr = new ByteArrayOutputStream();

    try (PrintStream prout = new PrintStream(bout, true, UTF8);
         PrintStream prerr = new PrintStream(berr, true, UTF8)) {
        System.out.println("Calling JDeprScan --Xprint-csv --Xload-dir " + deprcases);
        rval = Main.call(prout, prerr, "--Xprint-csv", "--Xload-dir", deprcases);
        System.out.println("JDeprScan returns " + rval);
    }

    System.out.println("----- stdout");
    new ByteArrayInputStream(bout.toByteArray()).transferTo(System.out);
    System.out.println("----- end stdout");
    System.out.println("----- stderr");
    new ByteArrayInputStream(berr.toByteArray()).transferTo(System.out);
    System.out.println("----- end stderr");

    List<String> actualList;
    try (ByteArrayInputStream bais = new ByteArrayInputStream(bout.toByteArray());
         InputStreamReader isr = new InputStreamReader(bais);
         BufferedReader br = new BufferedReader(isr)) {
        actualList = br.lines().collect(Collectors.toList());
    }

    Path expfile = Paths.get(System.getProperty("test.src"), EXPECTED);
    List<String> expectedList = Files.readAllLines(expfile);

    Set<String> actual = new HashSet<>(actualList.subList(1, actualList.size()));
    Set<String> expected = new HashSet<>(expectedList.subList(1, expectedList.size()));

    Set<String> diff1 = new HashSet<>(actual);
    diff1.removeAll(expected);
    Set<String> diff2 = new HashSet<>(expected);
    diff2.removeAll(actual);
    if (diff1.size() > 0) {
        System.out.println("Extra lines in output:");
        diff1.forEach(System.out::println);
    }

    if (diff2.size() > 0) {
        System.out.println("Lines missing from output:");
        diff2.forEach(System.out::println);
    }

    assertTrue(rval);
    assertEquals(berr.toByteArray().length, 0);
    assertEquals(actual.size(), actualList.size() - 1);
    assertEquals(diff1.size(), 0);
    assertEquals(diff2.size(), 0);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:61,代码来源:TestLoad.java


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