package lambda.list;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import pojo.Dome;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author: xxx
* @date 2021/5/14
**/
@Slf4j
public class GroupTest {
/***
* 初始化测试数组
* @date 2021/5/14
**/
private List<Dome> initArray() {
Dome dome1 = new Dome("张三", 11.0, 10);
Dome dome2 = new Dome("李四", 61.0, 11);
Dome dome3 = new Dome("王五", 26.0, 12);
Dome dome4 = new Dome("张三", 14.0, 14);
Dome dome5 = new Dome("王五", 24.0, 15);
Dome dome6 = new Dome("李四", 16.0, 16);
Dome dome7 = new Dome("赵六", 35.0, 17);
List<Dome> domes = new ArrayList<>();
domes.add(dome1);
domes.add(dome2);
domes.add(dome3);
domes.add(dome4);
domes.add(dome5);
domes.add(dome6);
domes.add(dome7);
log.info("domes : {}", domes);
return domes;
}
/***
* List分组
* @date 2021/5/13
**/
@Test
public void groupTest() {
List<Dome> domes = initArray();
Map<String, List<Dome>> collect = domes.stream().collect(Collectors.groupingBy(Dome::getName));
log.info(" ================================================ ");
for (String s : collect.keySet()) {
log.info(" {} -> {}", s, collect.get(s));
}
log.info(" ================================================ ");
for (Map.Entry<String, List<Dome>> stringListEntry : collect.entrySet()) {
log.info(" {} -> {}", stringListEntry.getKey(), stringListEntry.getValue());
}
/*
domes : [Dome{name='张三', money=11.0, age=10}, Dome{name='李四', money=61.0, age=11}, Dome{name='王五', money=26.0, age=12}, Dome{name='张三', money=14.0, age=14}, Dome{name='王五', money=24.0, age=15}, Dome{name='李四', money=16.0, age=16}, Dome{name='赵六', money=35.0, age=17}]
================================================
李四 -> [Dome{name='李四', money=61.0, age=11}, Dome{name='李四', money=16.0, age=16}]
张三 -> [Dome{name='张三', money=11.0, age=10}, Dome{name='张三', money=14.0, age=14}]
王五 -> [Dome{name='王五', money=26.0, age=12}, Dome{name='王五', money=24.0, age=15}]
赵六 -> [Dome{name='赵六', money=35.0, age=17}]
================================================
李四 -> [Dome{name='李四', money=61.0, age=11}, Dome{name='李四', money=16.0, age=16}]
张三 -> [Dome{name='张三', money=11.0, age=10}, Dome{name='张三', money=14.0, age=14}]
王五 -> [Dome{name='王五', money=26.0, age=12}, Dome{name='王五', money=24.0, age=15}]
赵六 -> [Dome{name='赵六', money=35.0, age=17}]
*/
}
}