这就是我想实现无法同时使用Java 8映射和maxBy操作
集团按类型的博客文章来纠正错误。在每种类型中,试图产生标题的名称并按最大长度减少。
这是我正在尝试使用的以下逻辑。
BlogPost b1 = new BlogPost("Story behind Harry Potter", "J.K.Rowling", BlogPostType.FICTION, 100);
BlogPost b2= new BlogPost("Java 8 Tutorial", "Vinay", BlogPostType.TECH, 10);
BlogPost b3 = new BlogPost("Python Tutorial", "Jim", BlogPostType.TECH, 20);
BlogPost b4 = new BlogPost("Mission Impossible", "Kim", BlogPostType.REVIEW, 40);
BlogPost b5 = new BlogPost("Bomb Blast", "Kenny", BlogPostType.NEWS, 200);
BlogPost b6 = new BlogPost("President Visits", "Laura", BlogPostType.NEWS, 400);
List<BlogPost> posts = Arrays.asList(b1,b2,b3,b4,b5,b6);
Map<String, Optional<String>> postsPer = posts.stream().collect(
Collectors.groupingBy(BlogPost::getType,
Collectors.mapping(BlogPost::getTitles,
Collectors.maxBy(Comparator.comparing(String::length)))));
而我无法弄清楚如何解决这个问题。 IDE将下面的线条指示为红色
mapping(BlogPost::getTitles
以及下面提到的错误/标记显示出我无法解决的问题。
Multiple markers at this line
- The method mapping(Function<? super T,? extends U>, Collector<? super U,A,R>) in the type Collectors is not applicable for the arguments (BlogPost::getTitles, Collector<String,capture#60-
of ?,Optional<String>>)
- The type BlogPost does not define getTitles(T) that is applicable here
下面是
package com.main.java8.streams.groupingby;
class BlogPost {
String title;
String author;
BlogPostType type;
int likes;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
/*@Override
public String toString() {
return "BlogPost [title=" + title + ", author=" + author + ", type=" + type + ", likes=" + likes + "]";
}*/
public BlogPostType getType() {
return type;
}
@Override
public String toString() {
return "BlogPost [title=" + title + "]";
}
public void setType(BlogPostType type) {
this.type = type;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public BlogPost(String title, String author, BlogPostType type, int likes) {
super();
this.title = title;
this.author = author;
this.type = type;
this.likes = likes;
}
}
package com.main.java8.streams.groupingby;
enum BlogPostType {
NEWS,
REVIEW,
GUIDE,
FICTION,
TECH
}
我不完全明白是怎么回事,但如果要我猜我会说'BlogPost :: getTitles'不是'Function <?超级T,?扩展U>' –