以 List<User> list=new ArrayList<>(); 为例
1. 排序,id小到大
第一种 list.sort((o1, o2) -> o1.getId() - o2.getId());
第二种按服务名排序,Service为实体类,reversed()代表倒序 list=list.stream().sorted(Comparator.comparing(Service::getName).reversed()).collect(Collectors.toList());
2. 打印list
items.forEach(System.out::println);
3. 删除指定ID
items.removeIf(e -> e.getId()==5);
4. 获取数组的最大数
int max = IntStream.of(arr).min().getAsInt();
5. 多线程方式获取数组的最大数
int max = IntStream.of(arr).parallel().max().getAsInt();
6. 启动线程并打印max变量
new Thread(()-> System.out.println(max)).start();
7.list去重 distinct(),并打印, 输出结果: 12
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(1);
list.add(2);
list.stream().distinct().forEach(System.out::print);
例
public class demo {
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList<>();
items.add(new Item(11, "小牙刷", 12.05 ));
items.add(new Item(5, "小日本马桶盖", 999.05 ));
items.add(new Item(7, "格力空调", 888.88 ));
items.add(new Item(17, "肥皂", 2.00 ));
items.add(new Item(9, "冰箱", 4200.00 ));
items.removeIf(e -> e.getId()==5);
int arr[] = {15, 48, 46, 85, 5, 2, 34,};
int max = IntStream.of(arr).min().getAsInt();
System.out.println("最大值:"+max);
//排序
items.sort((o1, o2) -> o1.getId() - o2.getId());
//打印
items.forEach(System.out::println);
List<User> userList = new ArrayList<>();
User user = new User();
user.setName("kkkd");
user.setId(87);
user.setPassword("1266448");
userList.add(user);
User user2 = new User();
user2.setName("cxx");
user2.setId(82);
user2.setPassword("14141");
userList.add(user2);
//获取id和name
List<User> userItem = userList.stream().map(e -> new User(e.getId(), e.getName())).collect(Collectors.toList());
userItem.forEach(System.out::println);
}
}
class Item {
Integer id;
String name;
@Override
public String toString() {
return "Item{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
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 Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Item(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
Double price;
}
class User{
Integer id;
String name;
String password;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
本文介绍Java中List集合的操作,包括排序、去重、获取最大值及多线程处理。演示了如何使用lambda表达式进行排序,如何通过stream API实现去重,并展示了多线程获取数组最大值的方法。
5769

被折叠的 条评论
为什么被折叠?



