我是Java 8的新手.我仍然不深入了解API,但我已经做了一个小的非正式基准测试来比较新Streams API与优秀旧Collections的性能.
测试包括过滤一个列表Integer,并为每个偶数计算平方根并将其存储在结果List中Double.
这是代码:
public static void main(String[] args) {
//Calculating square root of even numbers from 1 to N
int min = 1;
int max = 1000000;
List<Integer> sourceList = new ArrayList<>();
for (int i = min; i < max; i++) {
sourceList.add(i);
}
List<Double> result = new LinkedList<>();
//Collections approach
long t0 = System.nanoTime();
long elapsed = 0;
for (Integer i : sourceList) {
if(i % 2 == 0){
result.add(Math.sqrt(i));
} …Run Code Online (Sandbox Code Playgroud) 我有两个ArrayLists.
ArrayList A包含
['2009-05-18','2009-05-19','2009-05-21']
Run Code Online (Sandbox Code Playgroud)
ArrayList B包含 ['2009-05-18','2009-05-18','2009-05-19','2009-05-19','2009-05-20','2009-05-21','2009-05-21','2009-05-22']
我必须比较ArrayLst A和ArrayLst B. 结果ArrayList应该包含ArrayList中不存在的List .AllList结果应该是
[ '2009-05-20', '2009-05-22']
怎么比较?
在 Java 8 中,该类Comparator有一个非常漂亮的静态方法,它通过使用 a 的结果作为 的输入来将 a 组合Function为 a 。ComparatorFunctionComparator
我想做的是能够将Function对象与其他类型(例如 )组合Predicate,以使我的代码更具可读性,并使我的函数操作更强大。
例如,假设有一个Set<Person>where Personhas apublic String getName()方法。我希望能够过滤掉Person没有名称的对象。理想情况下,语法如下所示:
people.removeIf(Predicates.andThenTest(Person::getName, String::isEmpty));
Run Code Online (Sandbox Code Playgroud)
是否有任何内置方法可以将 aFunction与 a 之类的东西组合起来Predicate?我知道Function#andThen(Function),但这仅对将函数与其他函数组合有用,遗憾的是,Predicate没有extend Function<T, Boolean>。
PS我也知道我可以使用像 lambda 这样的 lambda p -> p.getName().isEmpty(),但我想要一种Predicate用Function.
你好,我在 java 8 中该怎么做(我知道它已经在 java 11 中),与不过滤这个相反
filter(date -> date.isEqual(today) && repository.isDateExist(date))
Run Code Online (Sandbox Code Playgroud)
我可以这样写
filter(date -> !date.isEqual(today) || !repository.isDateExist(date))
Run Code Online (Sandbox Code Playgroud)
但它很难读
我正在尝试 forEach 内部的方法引用
private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
people.forEach(p-> { if (predicate.test(p)){
System.out.println("Print here");}
});
}
Run Code Online (Sandbox Code Playgroud)
以上工作正常,但我想使用方法参考使它更短,但是它给出了编译问题。有什么办法让它发生?
private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
people.forEach({ if (predicate::test){
System.out.println("Print here");}
});
}
Run Code Online (Sandbox Code Playgroud) java ×5
java-8 ×4
java-stream ×2
arraylist ×1
collections ×1
function ×1
lambda ×1
performance ×1
predicate ×1