1.對列表進行分組,構建成一個map對象。node
鍵爲用戶名稱,值爲用戶對象列表。spa
Person p1 = new Person("張三", new BigDecimal("10.0")); Person p2 = new Person("王五", new BigDecimal("10.0")); Person p3 = new Person("李四", new BigDecimal("10.0")); Person p4 = new Person("李四", new BigDecimal("10.0")); Person p5 = new Person("張三", new BigDecimal("10.0")); List<Person> list = new ArrayList<>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); list.add(p5);
這個咱們以前寫代碼能夠須要寫成以下的方式:code
private Map<String,List<Person >> convertToMap(List<Person > list){ Map<String,List<Persion>> map=new HashMap<>(); for(Person p: list){ String name=p.getName(); if(map.containsKey(name){ map.get(name).add(p); } else{ List<Person> list=new ArrayList(); list.add(p); map.put(name,p); } } return map; }
寫了一大段代碼。對象
使用steam 就簡單了,一行代碼解決問題。blog
Map<String, List<Person>> collect = list.stream().collect(Collectors.groupingBy(person -> person.getName()));
System.out.println(collect);
2.將list 轉成 map 對象。ci
Person p1 = new Person("1","張三", new BigDecimal("10.0")); Person p2 = new Person("2","王五", new BigDecimal("10.0")); Person p3 = new Person("3","李四", new BigDecimal("10.0")); Person p4 = new Person("4","李四", new BigDecimal("10.0")); Person p5 = new Person("5","張三", new BigDecimal("10.0")); List<Person> list = new ArrayList<>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); list.add(p5);
上面的數據 咱們轉成 Map<String,Person> 對象。get
Map<String, Person> nodeMap = bpmSolUsergroups.stream().collect(Collectors.toMap(p->p.getId(), p -> p));io
3.對列表進行過濾class
public static void main(String[] args) { List<BpmCheckFile> filesInst =new ArrayList<>(); BpmCheckFile file1=new BpmCheckFile(); file1.setJumpId("1"); BpmCheckFile file11=new BpmCheckFile(); file11.setJumpId("1"); BpmCheckFile file2=new BpmCheckFile(); file2.setJumpId("2"); filesInst.add(file1); filesInst.add(file11); filesInst.add(file2); List<BpmCheckFile> files= filesInst.stream().filter(p->p.getJumpId()=="1").collect(Collectors.toList()); System.err.println(files.size()); }
對列表數據進行過濾。stream