我编写了一个简单的程序来与流的性能进行比较,以查找整数的最大形式列表。令人惊讶的是,我发现“流方式”的性能是“通常方式”的1/10。难道我做错了什么?是否有条件限制哪种Stream方法无效?有人能对此行为做出一个很好的解释吗?
“流方式”花费了80毫秒“流方式”花费了15毫秒请在下面找到代码
public class Performance {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
Random randomGenerator = new Random();
for (int i=0;i<40000;i++){
a.add(randomGenerator.nextInt(40000));
}
long start_s = System.currentTimeMillis( );
Optional<Integer> m1 = a.stream().max(Integer::compare);
long diff_s = System.currentTimeMillis( ) - start_s;
System.out.println(diff_s);
int e = a.size();
Integer m = Integer.MIN_VALUE;
long start = System.currentTimeMillis( );
for(int i=0; i < e; i++)
if(a.get(i) > m) m = a.get(i);
long diff = System.currentTimeMillis( ) - start;
System.out.println(diff);
}
Run Code Online (Sandbox Code Playgroud)
}
众所周知,在java-8中我们可以将函数/方法存储在变量中.通过使用以下方式.
@FunctionalInterface
public interface MyInterface {
public string getValue(int val1, int val2);
}
public class MyClass {
static String someFun(int val1, int val2) {
return ""+(val1+val2)
}
static BiFunction<Integer, Integer, String> testParamFun = (a,b) -> ""+(a+b);
public static void main(String[] args){
MyInterface intr = MyClass::someFun;
System.out.println(int.getValue(2,4)); // outpur will be "6"
/* i want this, but it give me compile time error?
I want to store that function in variable like i was doing in above case. */
MyInterface inter …Run Code Online (Sandbox Code Playgroud) 下面的代码给我一个编译错误
.filter(Book::getPrice >200)
Run Code Online (Sandbox Code Playgroud)
编译错误是:此表达式的目标类型应该是功能接口
public void skipData() {
List<Book> bookList = books.stream()
**.filter(Book::getPrice >200)**
.skip(5)
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
我的Book.java类如下所示:
public final class Book {
private String title;
private String genre;
private double price;
public Book(String title, String genre, double price) {
this.title = title;
this.genre = genre;
this.price = price;
}
public double getPrice() {
return price;
}
//other getters
}
Run Code Online (Sandbox Code Playgroud)
我试图在Eclipse(火星)和cmd线上运行它并看到同样的问题.
但如果我改变.filter(b -> b.getPrice() >200)它的工作原理.
我不清楚为什么方法参考在我的情况下不起作用.
Double::sum是添加双精度的方法参考,即.(a,b) -> a+b.
为什么JDK中没有用于减号的方法参考?是(a,b) -> a-b吗?
我有一个关于Java 8和列表的问题.是否可以比下面的代码更容易初始化List?
final List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();
weekScheduler.add(0, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(1, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(2, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(3, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(4, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(5, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(6, new ArrayList<ScheduleIntervalContainer>());
Run Code Online (Sandbox Code Playgroud) 我在Java 8 map操作中传递了一个Function,Intellij告诉我可以将其替换为lambda表达式。但是我不知道如何在不创建中间对象结构的情况下做到这一点。
这是我的工作:
List<DocumentResult> documentResults = objects.getObject().stream()
.map(new Function<ObjectType, DocumentResult>() {
@Override
public DocumentResult apply(ObjectType objectType) {
String[] keys = objectType.getStorageKey().getObjectName().split("/");
DocumentResult result = new DocumentResult(DocCategories.valueByLabel(keys[1]), DocCategoryGroups.valueByLabel(keys[2]), DocSubCategories.valueByLabel(keys[3]), keys[4], keys[5]);
result.setLink(objectType.getTempUrl().getFullUrl());
return result;
}
})
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我认为Intellij建议我这样做:
List<DocumentResult> documentResults = objects.getObject().stream()
.map(object -> object.getStorageKey().getObjectName().split("/"))
.map(tab -> new DocumentResult(DocCategories.valueByLabel(tab[1]), DocCategoryGroups.valueByLabel(tab[2]), DocSubCategories.valueByLabel(tab[3]), tab[4], tab[5]))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我不知道一种干净的方法来获取在匿名函数中检索到的objectType.getTempUrl()。getFullUrl()部分,有什么建议吗?
我试图迭代对象的ArrayList并打印出列表中每个对象的'name'属性.但是,即使我在Person类中有名称的getter方法,我也无法访问该对象的属性.这是一些代码:
ArrayList persons = new ArrayList<>();
persons.add(new Person("Name","Age"));
persons.add(new Person("Name1","Age1"));
persons.add(new Person("Name2","Age2"));
persons
.stream()
.forEach(e -> System.out.println(e.getName())); //giving an error
forEach(e -> System.out.println(e)); //no error
Run Code Online (Sandbox Code Playgroud)
它不允许我这样做.我只能在打印命令中使用'e',它打印对象的参考号.
任何帮助表示赞赏:)
我有列表{"100","5","1","300","7"},当我stream().sorted()用于此列表时,它给了我以下结果{"1","100","300","5","7"}.看起来它只按第一个数字排序.怎么了?
ArrayList<String> list = new ArrayList<>(Arrays.asList(
"100","5","1","300","7"
));
list.stream().sorted().forEach(e -> System.out.println(e));
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用此方法在JavaFx CSS中加载自定义字体
@font-face {
font-family: 'Roboto';
src: url('fonts/Roboto-Medium.ttf');
}
Run Code Online (Sandbox Code Playgroud)
我已经用正确的路径完成了所有正确的操作,但是出现了此错误
Nov 28, 2015 4:49:18 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not load @font-face font [file:/C:/Users/RootUser/Desktop/Java8%20projects/RemoteViewer/out/production/JavaFxApplication/application/fonts/Roboto-Medium.ttf]
Run Code Online (Sandbox Code Playgroud)
这是我的项目结构“截图”
请注意,我正在使用intellij Idea作为我的IDE。
这些测试的时序差别很大,但是经历了相同的实现.我想了解为什么时间不同.
private static final int ITERATIONS = 100;
private static final DataFactory RANDOM_DF = DataFactoryImpl.defaultInstance();
@Test // 6s
public void testGetMaxLength() throws Exception {
for ( int i = 1; i < ITERATIONS; i++ ) {
testGetMaxLength( i );
}
}
private void testGetMaxLength( final int length ) {
for ( int i = 0; i < ITERATIONS; i++ ) {
String word = RANDOM_DF.word().getMaxLength( length );
assertThat( word, not( isEmptyOrNullString() ) );
assertThat( word.length(), allOf( …Run Code Online (Sandbox Code Playgroud)