class User{
private String id;
private String code;
private String name;
}List list;這么個(gè)列表,我想單獨(dú)取出code,假設(shè)有5個(gè)數(shù)據(jù),有三個(gè)code是1,兩個(gè)code是2,我想用java8的stream的方法操作取出一個(gè)列表或者set,例如List這樣,里面放了一個(gè)1和一個(gè)2,就是同時(shí)去重,怎么寫誒
2 回答

慕田峪9158850
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
public static void main(String[] args) { List<User> users = new ArrayList<>(); users.add(new User("1","1","張三")); users.add(new User("2","1","李四")); users.add(new User("3","2","王五")); users.add(new User("4","2","小明")); users.add(new User("5","1","小三")); Set<String> codeExists = new HashSet<>(); users = users.stream().filter((V)->{ String code = V.getCode(); if(codeExists.contains(code)){ return false; }else{ codeExists.add(code); return true; } }).collect(Collectors.toList()); System.out.println(users);

POPMUISE
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
class User{ String code; public String getCode() { return code; } } public class Test { public static void main(String args[]){ List<User> users = new ArrayList<>(); users.stream() .collect(Collectors.groupingBy(User::getCode)) .keySet(); } }
先分組,分完組后只拿keySet就行了
添加回答
舉報(bào)
0/150
提交
取消