本文共 3050 字,大约阅读时间需要 10 分钟。
1.list转map
List的对象放到Map的value中
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account)); }List的对象放到Map的value中
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity())); }去掉重复Key,防止报错
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2)); }指定Map的创建类型
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new)); }详细见
2、stream().map(***)进行集合对象的转换,***为表达式
ListproductionsList list = productions.stream().map(BuyProduction::getProductionId).collect(Collectors.toList());
List<BuyProduction>转为List<Long> ,经过map()转化后,再collect(Collectors.toList())转为指定的List<Long>
List<PersonDto> personDto = person.stream().map(PersonService::convertPersonToPersonDto).collect(Collectors.toList());
也支持自定义方法进行Bean对象之间的映射方法convertPersonToPersonDto进行转化
MapcanBuyProductionsList retret.addAll(canBuyProductions.values().parallelStream() .map(t -> { OrderProductionEntity item = new OrderProductionEntity(); item.setCreateTime(createTime); item.setProductionId(t.getProductionId()); item.setDescription(t.getDescription()); item.setPriceShop(t.getPriceRaw()); item.setCurrencyType(t.getCurrencyType()); item.setName(t.getName()); item.setCount(buyProductionMap.get(t.getProductionId()).getCount()); item.setFeeFare(t.getFeeFare()); item.setProductionVersion(t.getProductionVersion()); return item; }).collect(Collectors.toList()));
3、Optional避免Null Point Exception的语法
public String getCity(User user) throws Exception{
return Optional.ofNullable(user)
.map(u-> u.getAddress())
.map(a->a.getCity())
.orElseThrow(()->new Exception("取指错误")); }
Optional.ofNullable(user)
.ifPresent(u->{
dosomething(u);
});
public User getUser(User user) {
return Optional.ofNullable(user) .filter(u->"zhangsan".equals(u.getName())) .orElseGet(()-> { User user1 = new User(); user1.setName("zhangsan"); return user1; }); }更多
4.StringJoiner
用于构造由分隔符分隔的字符序列,并可选择性地从提供的前缀开始和以提供的后缀结尾。省的再次通过StringBuffer或者StingBuilder拼接。
StringJoiner sj = new StringJoiner(":", "[", "]");
sj.add("G").add("S").add(""); String dString = sj.toString();[G:S:F]
5.sorted,limit排序以及取前10个
callVehicles .stream() .sorted(Comparator.comparing(QueueFieldVehicle::getStatus,Comparator.reverseOrder()) .thenComparing(QueueFieldVehicle::getUpdated_dt)) .limit(10) .collect(Collectors.toList()) ;
转载地址:http://fxadi.baihongyu.com/