1.Java8中对List去重
package test;
public class User {
private String userid;
private String username;
private String age;
private String address;
public User(String userid, String username, String age, String address) {
super();
this.userid = userid;
this.username = username;
this.age = age;
this.address = address;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [userid=" + userid + ", username=" + username + ", age=" + age + ", address=" + address + "]";
}
}
package test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class Test1 {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User("1","李大锤","23","南京"));
userList.add(new User("2","张无忌","18","西安"));
userList.add(new User("3","刘德华","26","苏州"));
userList.add(new User("4","郭靖","33","上海"));
userList.add(new User("1","李大锤","23","南京")); //id相同,其他数据也相同
userList.add(new User("3","带头大哥","36","杭州")); //id相同,其他数据不同
System.out.println(userList);
//根据userid去重
userList = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User :: getUserid))), ArrayList::new));
System.out.println(userList);
}
}
2.Java List.contains()方法:判断列表中是否包含指定元素
public static void main(String[] args){ List<String>list = new ArrayList<String>(); list.add("草莓"); //向列表中添加数据 list.add("香蕉"); //向列表中添加数据 list.add("菠萝"); //向列表中添加数据 for(int i=0;i<list.size();i++){ //通过循环输出列表中的内容 System.out.println(i+":"+list.get(i)); } String o = "苹果"; System.out.println("list对象中是否包含元素"+o+":"+list.contains(o)); //判断字符串中是否包含指定字符串对象 }