List集合的元素对象
public class Book {
//书名
private String bookName;
//类型
private int type;
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Book(String bookName, int type) {
this.bookName = bookName;
this.type = type;
}
}
分组
public class MapToList {
//对list进行分组
public void grouping(){
List<Book> list=new ArrayList<Book>();
list.add(new Book("校花贴身高手",1));
list.add(new Book("斗破苍穹",1));
list.add(new Book("斗罗大陆",2));
list.add(new Book("倚天独龙记",3));
Map<Integer, List<Book>> listMap = new HashMap<>();
//根据单位type对list集合进行分组
for (Book book : list) {
List<Book> tempList = listMap.get(book.getType());
/*如果取不到数据,那么直接new一个空的ArrayList**/
if (tempList == null) {
tempList = new ArrayList<>();
tempList.add(book);
listMap.put(book.getType(), tempList);
}
else {
/*某个sku之前已经存放过了,则直接追加数据到原来的List里**/
tempList.add(book);
}
}
//遍历分组里面的键
for(int skuId : listMap.keySet()){
//输出分组中的类型
System.out.println(((Book)listMap.get(skuId).get(0)).getType());
//遍历分组里面的集合里面的对象
for(Book warehouseMonitoringData:listMap.get(skuId)){
//输出对象里面的一个属性
System.out.println(warehouseMonitoringData.getBookName());
}
}
}
//测试
public static void main(String[] args) {
MapToList mapToList = new MapToList();
mapToList.grouping();
}
}