本文整理匯總了Java中java.util.stream.Stream.forEach方法的典型用法代碼示例。如果您正苦於以下問題:Java Stream.forEach方法的具體用法?Java Stream.forEach怎麽用?Java Stream.forEach使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.stream.Stream
的用法示例。
在下文中一共展示了Stream.forEach方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: mirror
import java.util.stream.Stream; //導入方法依賴的package包/類
public QuadBuilder mirror() {
if(facingMap.containsKey(last)) {
Stream<Vector3> stream = Arrays.stream(facingMap.get(last).getVectors());
switch(last) {
case DOWN:
case UP:
stream.forEach(vec -> {
vec.subtract(0.5D).rotate(EnumFacing.Axis.Y, 180).add(0.5D);
});
break;
case NORTH:
case SOUTH:
stream.forEach(vec -> {
vec.subtract(0.5D).rotate(EnumFacing.Axis.X, 180).add(0.5D);
});
break;
case EAST:
case WEST:
stream.forEach(vec -> {
vec.subtract(0.5D).rotate(EnumFacing.Axis.Z, 180).add(0.5D);
});
break;
}
}
return this;
}
示例2: toArray
import java.util.stream.Stream; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
public static Class<? extends Packet>[] toArray(Stream<Class<? extends Packet>> packets) {
TreeMap<Integer, Class<? extends Packet>> map = new TreeMap<>();
packets.forEach(packet -> {
PacketInfo info = packet.getAnnotation(PacketInfo.class);
map.put(info.id(), packet);
});
if (map.size() == 0) {
return new Class[0];
}
Class<? extends Packet>[] array = new Class[map.lastKey() + 1];
map.forEach((id, packet) -> array[id] = packet);
return array;
}
示例3: parseReleaseGroupMetaFile
import java.util.stream.Stream; //導入方法依賴的package包/類
private void parseReleaseGroupMetaFile(List<Album> albums) {
Map<String, List<Album>> releaseGroupIdAlbumMap = albums.stream()
.filter(album -> !StringUtils.isEmpty(album.getReleaseGroupId()))
.collect(Collectors.groupingBy(Album::getReleaseGroupId));
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(releaseGroupMetaFilePath))) {
Stream<String[]> rows = stream.map(strRow -> strRow.split(TAB_SYMBOL));
rows.forEach(row -> {
List<Album> albumList = releaseGroupIdAlbumMap.get(row[0]);
if (albumList != null) {
JsonDateDay releasedDate = ParserUtils.parseDateDay(row[2], row[3], row[4]);
albumList.forEach(album -> album.setReleasedDate(releasedDate));
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
示例4: readCodePoints
import java.util.stream.Stream; //導入方法依賴的package包/類
private List<CodePoint> readCodePoints() {
try {
List<CodePoint> codePoints = new ArrayList<>();
Stream<String> stream = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("/codepoints"))).lines();
stream.forEach(line -> {
String[] parts = line.split("\\s", 2);
int code = Integer.parseInt(parts[1], 16);
codePoints.add(new CodePoint(parts[0], code));
});
return codePoints;
} catch(Exception e) {
throw new RuntimeException("Failed to read code points", e);
}
}
示例5: fixPermissions
import java.util.stream.Stream; //導入方法依賴的package包/類
public void fixPermissions() throws IOException {
try {
Set<PosixFilePermission> filePermissions = Files.getPosixFilePermissions(executable);
Stream<PosixFilePermission> requiredPermissions = Stream
.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_EXECUTE);
requiredPermissions.forEach(requiredPermission -> {
filePermissions.add(requiredPermission);
});
Files.setPosixFilePermissions(executable, filePermissions);
} catch (UnsupportedOperationException e) {
// windows -.-
}
}
示例6: spread
import java.util.stream.Stream; //導入方法依賴的package包/類
private void spread() {
World world = GameState.getGameWorld();
ThreadLocalRandom random = ThreadLocalRandom.current();
int spreadSize = UHC.getInstance().getMainConfig().getWorldBorderInitialSize();
Stream<? extends Player> players = Bukkit.getServer().getOnlinePlayers().stream().filter(player -> player.getGameMode() != GameMode.SPECTATOR);
players.forEach(player -> player.teleport(generateSafe(spreadSize, world, random)));
}
示例7: test2
import java.util.stream.Stream; //導入方法依賴的package包/類
/**
* 刪除不影響流
*/
public void test2(){
c1.add(1);
c1.add(2);
c1.add(3);
c2.add(3);
c2.add(4);
c2.add(5);
Stream<Integer> s=Stream.concat(c1.stream(), c2.stream());
c1.remove(1);
s.forEach(a->{
System.out.println(a);
});;
}
示例8: createCustomArrayStream
import java.util.stream.Stream; //導入方法依賴的package包/類
public void createCustomArrayStream(){
Employee emp1 = new Employee();
Employee emp2 = new Employee();
Stream<Employee> emptyRecs = Stream.of(emp1, emp2);
Consumer<Employee> showRecs = System.out::println;
emptyRecs.forEach(showRecs);
}
示例9: rerunHistoryEntriesById
import java.util.stream.Stream; //導入方法依賴的package包/類
/**
* Handle snippet reevaluation commands: {@code /<id>}. These commands are a
* sequence of ids and id ranges (names are permitted, though not in the
* first position. Support for names is purposely not documented).
*
* @param rawargs the whole command including arguments
*/
private void rerunHistoryEntriesById(String rawargs) {
ArgTokenizer at = new ArgTokenizer("/<id>", rawargs.trim().substring(1));
at.allowedOptions();
Stream<Snippet> stream = argsOptionsToSnippets(state::snippets, sn -> true, at);
if (stream != null) {
// successfully parsed, rerun snippets
stream.forEach(sn -> rerunSnippet(sn));
}
}
示例10: main
import java.util.stream.Stream; //導入方法依賴的package包/類
public static void main(String[] args) {
List<String> lines = DataStub.getLines();
Stream<String> stream = lines.stream();
stream.reduce((a, b) -> a.length() > b.length() ? a : b)
.ifPresent(System.out::println);
// below line will throw the exception
stream.forEach(System.out::println);
}
示例11: addAll
import java.util.stream.Stream; //導入方法依賴的package包/類
default <T extends JsonElement> JsonObjectBuilder addAll(Stream<Map.Entry<String, T>> stream, boolean deepCopy) {
Preconditions.checkNotNull(stream, "stream");
stream.forEach(e -> {
if (e == null || e.getKey() == null) {
return;
}
add(e.getKey(), e.getValue(), deepCopy);
});
return this;
}
示例12: complete
import java.util.stream.Stream; //導入方法依賴的package包/類
public static List<String> complete(String prefix, Stream<String> options) {
final String prefixLower = prefix.toLowerCase();
final int pos = prefixLower.lastIndexOf(' ');
final List<String> matches = new ArrayList<>();
options.forEach(option -> {
if(option.toLowerCase().startsWith(prefixLower)) {
matches.add(pos == -1 ? option : option.substring(pos + 1));
}
});
Collections.sort(matches);
return matches;
}
示例13: isValid
import java.util.stream.Stream; //導入方法依賴的package包/類
/**
* Chronosome is valid if:
* <ul>
* <li>all the ChronoGenes are valid</li>
* <li>no duplicate genes</li>
* <li>no duplicate ChronoFrequency</li>
* <li>ChronoPatterns don't share temporal inclusions</li>
* </ul>
*
* @return Chronosome validity
*/
@Override
public boolean isValid() {
//dupe genes check
final AtomicBoolean dupeGenes = new AtomicBoolean(false);
Stream<ChronoUnit> chronoUnits = getGenes().stream()
.filter(chronoGene -> chronoGene.getAllele() instanceof ChronoPattern)
.map(chronoGene -> ((ChronoPattern) chronoGene.getAllele()).getChronoScaleUnit().getChronoUnit())
.distinct();
chronoUnits.forEach(
chronoUnit -> {
ISeq<ChronoPattern> unitPatterns = getGenes().stream()
.filter(chronoGene -> chronoGene.getAllele() instanceof ChronoPattern)
.map(chronoGene -> (ChronoPattern) chronoGene.getAllele())
.filter(chronoPattern -> chronoPattern.getChronoScaleUnit().getChronoUnit().equals(chronoUnit))
.collect(ISeq.toISeq());
if (unitPatterns.size() > 1) {
Set<Integer> temporalInclusionSet = Sets.newHashSet();
unitPatterns.forEach(
chronoPattern -> {
if (!chronoPattern.getTemporalValue().isPresent()) {
dupeGenes.set(true);
} else {
int patternValue = chronoPattern.getTemporalValue().getAsInt();
if (temporalInclusionSet.contains(patternValue)) {
dupeGenes.set(true);
} else {
temporalInclusionSet.add(patternValue);
}
}
}
);
}
}
);
if (dupeGenes.get()) {
return false;
}
boolean hasChronoFrequency = false;
for (ChronoGene gene : genes) {
if (!gene.isValid()) {
return false;
}
if (gene.getAllele() instanceof ChronoFrequency) {
if (hasChronoFrequency) {
//multiple chrono frequencies aren't allowed
return false;
}
hasChronoFrequency = true;
}
}
return true;
}
示例14: testWeatherServiceLazyAndCache
import java.util.stream.Stream; //導入方法依賴的package包/類
@Test
public void testWeatherServiceLazyAndCache(){
/**
* Arrange WeatherService --> WeatherWebApi --> Countify --> FileRequest
*/
ICounter<String, Stream<String>> req = Countify.of(new FileRequest()::getContent);
// Function<String, Iterable<String>> cache = Cache.memoize(req);
WeatherService api = new WeatherServiceCache(new WeatherWebApi(req::apply));
/**
* Act and Assert
*/
Stream<Location> locals = api.search("Porto");
assertEquals(1, req.getCount());
locals = locals.filter(l -> l.getLatitude() > 0 );
assertEquals(1, req.getCount());
/**
* Counts 1 request when iterates to get the first Location
*/
Location loc = locals.iterator().next();
assertEquals(1, req.getCount());
Stream<WeatherInfo> infos = loc.getPastWeather(of(2017,02,01), of(2017,02,28));
assertEquals(2, req.getCount());
infos = infos.filter(info ->
info.getDescription().toLowerCase().contains("sun"));
Stream<Integer> temps = infos.map(WeatherInfo::getTempC);
temps = temps.distinct();
assertEquals(2, req.getCount());
/**
* When we iterate over the pastWeather then we make one more request
*/
assertEquals(5, temps.count()); // iterates all items
assertEquals(2, req.getCount());
temps = api.search("Porto")
.findFirst().get()
.getPastWeather(of(2017,02,01), of(2017,02,28))
.filter(info -> info.getDescription().toLowerCase().contains("sun"))
.map(WeatherInfo::getTempC);
assertEquals((long) 20, (long) temps.skip(2).findFirst().get()); // another iterator
assertEquals(3, req.getCount());
/**
* getting a sub-interval of past weather should return from cache
*/
infos = loc.getPastWeather(of(2017,02,05), of(2017,02,18));
infos.iterator().next();
assertEquals(3, req.getCount());
/**
* getting a new interval gets from IO
*/
infos = loc.getPastWeather(of(2017,02,15), of(2017,03,15));
infos.forEach((item) -> {}); // Consume all to add all itens in cache
assertEquals(4, req.getCount());
/**
* getting a sub-interval of past weather should return from cache
*/
infos = loc.getPastWeather(of(2017,02,20), of(2017,03,10));
infos.iterator().next();
assertEquals(4, req.getCount());
}
示例15: parse
import java.util.stream.Stream; //導入方法依賴的package包/類
/**
* Parses all class files from the given archive stream and returns
* all target locations.
*/
public Set<Location> parse(Stream<? extends Archive> archiveStream) {
archiveStream.forEach(archive -> parse(archive, CLASS_FINDER));
return waitForTasksCompleted();
}