方法实现
代码复制运行即可实现
public class Book implements Comparable<Book>{
private Integer id;
private String name;
private String type;
public Book(Integer id, String name, String type) {
super();
this.id = id;
this.name = name;
this.type = type;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", type=" + type + "]";
}
@Override
public int compareTo(Book book) {
return this.id-book.id;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListTest {
public static List<Book> prepareData() {
List<Book> bookList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
bookList.add(new Book(i, "book" + i, "心理学"));
}
for (int i = 3; i < 6; i++) {
bookList.add(new Book(i, "book" + i, "管理学"));
}
for (int i = 6; i < 9; i++) {
bookList.add(new Book(i, "book" + i, "编程"));
}
return bookList;
}
public static void main(String[] args) {
List<Book> bookList = prepareData();
/** 寻找的书籍Id **/
ArrayList<Integer> ids = new ArrayList<>();
ids.add(8);
ids.add(5);
ids.add(2);
ids.add(6);
List<Book> result = null;
/** List过滤 **/
System.out.println("************List过滤");
result = bookList.stream().filter((Book b) -> ids.contains(b.getId())).collect(Collectors.toList());
Collections.shuffle(result);/** 打乱List排序 **/
if (result != null && !result.isEmpty()) {
result.forEach(
(Book b) -> System.out.println(String.format("%s-%s-%s", b.getId(), b.getName(), b.getType())));
}
/**读取集合中的某个属性**/
List<Integer> a = bookList.stream().map(Book::getId).collect(Collectors.toList());
if (a != null && !a.isEmpty()) {
System.out.println("collect="+a.toString());
}
/** List 排序 **/
System.out.println("************List排序");
Collections.sort(result);
if (result != null && !result.isEmpty()) {
result.forEach(
(Book b) -> System.out.println(String.format("%s-%s-%s", b.getId(), b.getName(), b.getType())));
}
/** List 统计 **/
System.out.println("************List统计");
long count = bookList.stream().filter(x -> x.getId()>5).count();
System.out.println("id大于5的元素统计:"+String.valueOf(count));
/** list分组 **/
System.out.println("************List分组");
Map<String, List<Book>> groupBy = bookList.stream().collect(Collectors.groupingBy(Book::getType));
System.out.println("groupBy:" + groupBy);
}
}
后言
- 文章是个人知识点整理总结,如有错误和不足之处欢迎指正。
- 如有疑问、或希望与笔者探讨技术问题(包括但不限于本章内容),欢迎添加笔者微信(o815441)。请备注“探讨技术问题”。欢迎交流、一起进步。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69828.html