import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
public class LocalTest {
private List<Car> cars = Lists.newArrayList();
@Before
public void init() {
cars.addAll(Arrays.asList(
new Car("Benz", new BigDecimal(999999)),
new Car("BMW", new BigDecimal(10000)),
new Car("BMW", new BigDecimal(888888))
));
}
@Test
public void toMapTest() {
//以brand和price属性分别作为key和value创建map,若集合中存在key重复的元素,就取后一个
Map<String, BigDecimal> collect = cars.stream().collect(Collectors.toMap(Car::getBrand, Car::getPrice, (x, y) -> y));
//以brand为key,将集合分组,每个brand对应一个Car集合
Map<String, List<Car>> collect1 = cars.stream().collect(Collectors.groupingBy(Car::getBrand));
//将集合按是否满足partitioningBy中的断言函数为标准,分成两个集合
Map<Boolean, List<Car>> bn = cars.stream().collect(Collectors.partitioningBy(k -> "BMW".equals(k.getBrand())));
log.info("log {} \n {} \n{}", collect, collect1, bn);
}
@Data
static class Car {
private String brand;
private BigDecimal price;
public Car() {
}
public Car(String brand, BigDecimal price) {
this.brand = brand;
this.price = price;
}
}
}