Last active
March 29, 2023 11:29
-
-
Save fwrq41251/b59095e8700c7d2ed6da1adc697ed7eb to your computer and use it in GitHub Desktop.
勤怠学习会20230329 java stream api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.winry; | |
import org.openjdk.jmh.annotations.Benchmark; | |
import org.openjdk.jmh.annotations.BenchmarkMode; | |
import org.openjdk.jmh.annotations.Mode; | |
import org.openjdk.jmh.runner.RunnerException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.stream.IntStream; | |
import java.util.stream.Stream; | |
//@Fork(value = 1, warmups = 2) | |
@BenchmarkMode(Mode.AverageTime) | |
public class Main { | |
private static final List<String> DATA = getData(); | |
public static void main(String[] args) throws RunnerException { | |
// Options opt = new OptionsBuilder() | |
// .include(Main.class.getSimpleName()) | |
// .build(); | |
// new Runner(opt).run(); | |
new Main().peek(); | |
} | |
@Benchmark | |
public List<Integer> filterMap() { | |
return DATA.stream() | |
.filter(s -> { | |
try { | |
Integer.parseInt(s); | |
return true; | |
} catch (NumberFormatException e) { | |
return false; | |
} | |
}) | |
.map(Integer::parseInt).toList(); | |
} | |
@Benchmark | |
public List<Integer> flatMap() { | |
return DATA.stream() | |
.flatMap(s -> { | |
try { | |
return Stream.of(Integer.parseInt(s)); | |
} catch (NumberFormatException e) { | |
return Stream.empty(); | |
} | |
}).toList(); | |
} | |
@Benchmark | |
public List<Integer> mapMulti() { | |
return DATA.stream() | |
.<Integer>mapMulti((s, consumer) -> { | |
try { | |
consumer.accept(Integer.parseInt(s)); | |
} catch (NumberFormatException ignore) { | |
} | |
}).toList(); | |
} | |
@Benchmark | |
public List<Integer> forLoop() { | |
var list = new ArrayList<Integer>(); | |
for (var s : DATA) { | |
try { | |
list.add(Integer.parseInt(s)); | |
} catch (NumberFormatException ignore) { | |
} | |
} | |
return list; | |
} | |
public void peek() { | |
DATA.stream().peek(System.out::println).count(); | |
} | |
public void forEach() { | |
DATA.stream().forEach(System.out::println); | |
} | |
private static List<String> getData() { | |
var random = new Random(); | |
return IntStream.range(0, 5_000_000) | |
.mapToObj(i -> nextInt(random) ? String.valueOf(random.nextInt()) : "cant parse") | |
.toList(); | |
} | |
private static boolean nextInt(Random random) { | |
return random.nextDouble() > 0.9; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment