本文整理汇总了Java中java.util.stream.IntStream类的典型用法代码示例。如果您正苦于以下问题:Java IntStream类的具体用法?Java IntStream怎么用?Java IntStream使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
IntStream类属于java.util.stream包,在下文中一共展示了IntStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: toString
import java.util.stream.IntStream; //导入依赖的package包/类
@Override
public String toString(){
StringBuffer result = new StringBuffer();
result.append( String.format( "Column name : %s\n" , getColumnName() ) );
result.append( String.format( "Column type : %s<" , getColumnType() ) );
result.append( columnContainer.entrySet().stream()
.map( entry -> String.format( "%s" , entry.getValue().getColumnType() ) )
.collect( Collectors.joining( "," ) )
);
result.append( ">\n" );
result.append( "--------------------------\n" );
IntStream.range( 0 , size() )
.forEach( i -> {
result.append( String.format( "CELL-%d: %s\n" , i , get( i ).toString() ) );
} );
return result.toString();
}
示例2: generateBigXmlFile
import java.util.stream.IntStream; //导入依赖的package包/类
/**
* Generate a BIG xml file: temporary/bigfile.xml
*/
@Test
@Ignore
public void generateBigXmlFile() throws IOException {
// make temporary/ dir if it doesn't exist
Path temporaryPath = Paths.get(Constants.TMP_PATH);
if (!Files.exists(temporaryPath)) {
Files.createDirectory(temporaryPath);
}
// dump loads of xml in temporary/bigfile.xml
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(Constants.BIG_XML_FILE_PATH));
PrintWriter printWriter = new PrintWriter(bufferedWriter);
printWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
printWriter.println("<rootelement>");
IntStream
.rangeClosed(1, Integer.parseInt(TestProperties.getProperty("com.guido.test.upload.bigfile")))
.forEach(i -> printWriter.println( String.format("<childelement id=\"%d\">HELLO%10d</childelement>", i, i) ));
printWriter.println("</rootelement>");
printWriter.flush();
printWriter.close();
}
示例3: generatePost
import java.util.stream.IntStream; //导入依赖的package包/类
private String generatePost(final List<SlackMessagePosted> publicaties) {
String content = "";
content += "Hieronder is de lijst met #publicaties van deze week (" + WeekUtil.getWeekNumber() + ") te vinden. Veel leesplezier!";
content += System.lineSeparator();
content += IntStream.range(0, publicaties.size())
.mapToObj(index -> (index + 1) + ". " + messageParser.parse(publicaties.get(index).getMessageContent()))
.reduce("", (identity, accu) -> identity + System.lineSeparator() + accu);
content += System.lineSeparator() + System.lineSeparator();
String publicators = publicaties.stream()
.map(message -> message.getSender().getUserName())
.distinct()
.reduce((identity, accu) -> identity + ", @" + accu).get();
content += "De lijst is deze week mogelijk gemaakt door @" + publicators + ". Bedankt!";
content += System.lineSeparator() + System.lineSeparator();
content += "Kom je een interessante publicatie (foto/video/textueel) tegen? Deel deze dan in het #publicaties kanaal zodat iedereen er van kan leren :slightly_smiling_face:";
content += System.lineSeparator() + System.lineSeparator();
content += "Nog een fijne zondag!";
return content;
}
示例4: test
import java.util.stream.IntStream; //导入依赖的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
示例5: clientToServerBackpressure
import java.util.stream.IntStream; //导入依赖的package包/类
@Test
public void clientToServerBackpressure() throws InterruptedException {
ReactorNumbersGrpc.ReactorNumbersStub stub = ReactorNumbersGrpc.newReactorStub(channel);
Flux<NumberProto.Number> reactorRequest = Flux
.fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator)
.doOnNext(i -> System.out.println(i + " --> "))
.doOnNext(i -> updateNumberOfWaits(lastValueTime, numberOfWaits))
.map(BackpressureIntegrationTest::protoNum);
Mono<NumberProto.Number> reactorResponse = stub.requestPressure(reactorRequest);
StepVerifier.create(reactorResponse)
.expectNextMatches(v -> v.getNumber(0) == NUMBER_OF_STREAM_ELEMENTS - 1)
.expectComplete()
.verify(Duration.ofSeconds(5));
assertThat(numberOfWaits.get()).isEqualTo(1);
}
示例6: apply_Right
import java.util.stream.IntStream; //导入依赖的package包/类
/**
<hr>
<h3>
Created : Alexandre Bolot 10/01 <br>
Modified : Alexandre Bolot 10/01
</h3>
<hr>
*/
@Test
public void apply_Right ()
{
long youngAmount;
long oldAmount;
for (int i = 0; i < 1000; i++)
{
people = new ArrayList8<Person>()
{{
IntStream.range(0, randBetween(5, 20)).forEach(j -> add(randPerson(lifespan, true)));
IntStream.range(0, randBetween(5, 20)).forEach(k -> add(randPerson(lifespan, false)));
}};
youngAmount = people.stream().filter(person1 -> person1.data().age() < lifespan).count();
oldAmount = people.stream().filter(person -> person.data().age() >= lifespan).count();
assertEquals(youngAmount + oldAmount, people.size());
lifespanRule.apply(new Context(people));
assertEquals(youngAmount, people.size());
}
}
示例7: genPermutation
import java.util.stream.IntStream; //导入依赖的package包/类
/**
* Algorithm 7.42: GenPermutation
* <p>Generates a random permutation psy ∈ upper_psy_n following Knuth’s shuffle algorithm</p>
*
* @param upper_n the permutation size
* @return a random permutation following Knuth's shuffle algorithm (permutation is 0 based, to mirror java indices)
*/
public List<Integer> genPermutation(int upper_n) {
Integer[] upper_i = IntStream.range(0, upper_n).boxed()
.collect(Collectors.toList()).toArray(new Integer[0]);
List<Integer> psy = new ArrayList<>();
// indices are 0 base, as opposed to the 1 based in the algorithm
for (int i = 0; i < upper_n; i++) {
int k = randomGenerator.randomIntInRange(i, upper_n - 1);
psy.add(upper_i[k]);
upper_i[k] = upper_i[i];
}
return psy;
}
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:23,代码来源:MixingAuthorityAlgorithms.java
示例8: main
import java.util.stream.IntStream; //导入依赖的package包/类
public static void main(String[] args)
throws IOException
{
File mainDir = new File("mturk/annotation-task/data/final");
File trainingData = new File(mainDir, "train.tsv");
File devData = new File(mainDir, "dev.tsv");
File testData = new File(mainDir, "test.tsv");
// random
IntStream.range(0, 3).parallel().forEach(value -> {
try {
runExperiment(new RandomClassifier((long) value), trainingData, devData, testData);
}
catch (IOException e) {
e.printStackTrace();
}
});
// LM
runExperiment(new LMClassifier("apu", 8090), trainingData, devData, testData);
}
示例9: verifyConfigReports
import java.util.stream.IntStream; //导入依赖的package包/类
protected void verifyConfigReports(ConfigurationReport configuration, String nameSuffix, List<Report> merged) {
// check the expected number of configuration reports - should be same as the number of generated sections
assertThatReport(configuration)
.as("Configuration report should contain an exact number of test config sub-reports")
.hasNumberOfSubReports(EXPECTED_NUMBER_OF_SECTIONS);
// for each configuration sub-report
IntStream.range(0, EXPECTED_NUMBER_OF_SECTIONS).forEach(index -> {
Report reportOnIndex = configuration.getSubReports().get(index);
defaultCheckOfIfMergedOrContainsGeneratedSubReports(merged, index, reportOnIndex);
assertThatReport(reportOnIndex)
.as("The config report should have same name that was generated for the index <%s> ", index)
.hasName(getConfigReportName(index, nameSuffix));
});
}
示例10: getTally
import java.util.stream.IntStream; //导入依赖的package包/类
public List<Long> getTally() throws InvalidDecryptionProofException {
TallyData tallyData = bulletinBoardService.getTallyData();
List<DecryptionProof> decryptionProofs = tallyData.getDecryptionProofs();
List<BigInteger> publicKeyShares = tallyData.getPublicKeyShares();
List<Encryption> finalShuffle = tallyData.getFinalShuffle();
List<List<BigInteger>> partialDecryptions = tallyData.getPartialDecryptions();
Stopwatch decryptionProofCheckWatch = Stopwatch.createStarted();
if (!tallyingAuthoritiesAlgorithm.checkDecryptionProofs(decryptionProofs, publicKeyShares, finalShuffle,
partialDecryptions)) {
throw new InvalidDecryptionProofException("An invalid decryption proof was found");
}
decryptionProofCheckWatch.stop();
perfLog.info(String.format("Administration : checked decryption proofs in %dms",
decryptionProofCheckWatch.elapsed(TimeUnit.MILLISECONDS)));
List<BigInteger> decryptions = tallyingAuthoritiesAlgorithm.getDecryptions(finalShuffle, partialDecryptions);
List<List<Boolean>> votes = tallyingAuthoritiesAlgorithm.getVotes(decryptions, totalCandidateCount);
// Additional verifications on the votes validity may be performed here.
return IntStream.range(0, totalCandidateCount)
.mapToLong(i -> votes.stream().filter(vote -> vote.get(i)).count())
.boxed().collect(Collectors.toList());
}
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:24,代码来源:ElectionAdministrationSimulator.java
示例11: testBitsetStream
import java.util.stream.IntStream; //导入依赖的package包/类
@Test(dataProvider = "cases")
public void testBitsetStream(String name, IntStream data) {
BitSet bs = new BitSet();
long setBits = data.distinct()
.peek(i -> bs.set(i))
.count();
assertEquals(bs.cardinality(), setBits);
assertEquals(bs.cardinality(), bs.stream().reduce(0, (s, i) -> s+1));
PrimitiveIterator.OfInt it = bs.stream().iterator();
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
assertTrue(it.hasNext());
assertEquals(it.nextInt(), i);
}
assertFalse(it.hasNext());
}
示例12: getBasicPlayerInfo
import java.util.stream.IntStream; //导入依赖的package包/类
/**
* Returns an {@link Optional} of a {@link List} of {@link Player} objects, containing all
* players on the server.
*
* @return an {@link Optional} containg a {@link List} of {@link Player Players} or an empty
* {@link Optional} incase the query failed.
*/
public Optional<List<Player>> getBasicPlayerInfo() {
List<Player> players = null;
if (send(PACKET_GET_BASIC_PLAYERINFO)) {
final byte[] reply = receiveBytes();
if (Objects.nonNull(reply)) {
final ByteBuffer buffer = wrapReply(reply);
final int numberOfPlayers = buffer.getShort();
players = new ArrayList<>();
for (int i = 0; i < numberOfPlayers; i++) {
final byte len = buffer.get();
final byte[] playerName = new byte[len];
IntStream.range(0, len).forEach(j -> playerName[j] = buffer.get());
players.add(new Player(new String(playerName), buffer.getInt()));
}
}
}
return Optional.ofNullable(players);
}
示例13: getHeaderTokens
import java.util.stream.IntStream; //导入依赖的package包/类
/**
* Returns the header string tokens for the frame
* @param frame the frame to create header tokens
* @return the header tokens
*/
private String[] getHeaderTokens(DataFrame<?,?> frame) {
final int colCount = frame.colCount() + 1;
final String[] header = new String[colCount];
final Class<?> columnKeyType = frame.cols().keyType();
final Printer<Object> printer = formats.getPrinterOrFail(columnKeyType, Object.class);
IntStream.range(0, colCount).forEach(colIndex -> {
if (colIndex == 0) header[colIndex] = "Index";
else {
final Object colKey = frame.cols().key(colIndex - 1);
final String colText = printer.apply(colKey);
header[colIndex] = colText;
}
});
return header;
}
示例14: testClose
import java.util.stream.IntStream; //导入依赖的package包/类
@Test
public void testClose() {
AtomicInteger before = new AtomicInteger();
AtomicInteger onClose = new AtomicInteger();
Supplier<Stream<Integer>> s = () -> {
before.set(0); onClose.set(0);
return Stream.of(1, 2).peek(e -> before.getAndIncrement());
};
s.get().flatMap(i -> Stream.of(i, i).onClose(onClose::getAndIncrement)).count();
assertEquals(before.get(), onClose.get());
s.get().flatMapToInt(i -> IntStream.of(i, i).onClose(onClose::getAndIncrement)).count();
assertEquals(before.get(), onClose.get());
s.get().flatMapToLong(i -> LongStream.of(i, i).onClose(onClose::getAndIncrement)).count();
assertEquals(before.get(), onClose.get());
s.get().flatMapToDouble(i -> DoubleStream.of(i, i).onClose(onClose::getAndIncrement)).count();
assertEquals(before.get(), onClose.get());
}
示例15: testCharAt
import java.util.stream.IntStream; //导入依赖的package包/类
@Test(dataProvider = "provider")
public void testCharAt(String str, char[] expected) {
map.get(str)
.forEach(
(source, data) -> {
IntStream
.range(0, str.length())
.forEach(
i -> assertEquals(
str.charAt(i),
expected[i],
String.format(
"testing String(%s).charAt(%d), source : %s, ",
escapeNonASCIIs(data),
i, source)));
});
}