import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
People p1 = new People("1","李红", 50);
People p2 = new People("2","李逵", 20);
List<People> list = new ArrayList<People>();
list.add(p1);
list.add(p2);
People p3 = new People("1","诸葛亮", 80);
People p4 = new People("2","李逵", 40);
List<People> list1 = new ArrayList<People>();
list1.add(p3);
list1.add(p4);
// 1、java lambda表达式检查list集合是否存在某个值
boolean bool = list.stream().anyMatch(people -> people.getId().equals("3"));
System.out.println("bool:"+ bool);
List<People> data = list.stream().filter(people -> people.getId().equals("1")).collect(Collectors.toList());
if(data != null && !data.isEmpty()){
for (People people : data){
System.out.println("id="+ people.getId() +":name="+ people.getName());
}
}
List<People> peopleList = new ArrayList<People>();
//2、遍历两个list 取交集
list.forEach(people -> {
People people1 = list1.stream().filter(people2 ->
people.getId().equals(people2.getId())).findFirst().orElse(null);
if(people1 != null){
int score = people.getScore() == null ? 0: people.getScore();
int score1 = people1.getScore() == null ? 0: people1.getScore();
people1.setScore(score + score1);
}
peopleList.add(people1);
});
if(peopleList != null && !peopleList.isEmpty()){
for (People people : peopleList){
System.out.println("id="+ people.getId() +":name="+ people.getName()+":score ="+ people.getScore());
}
}
// 3获取某个对象的list集合 并去重复
List<String> nameList = list.stream().map(e -> e.getName()).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
System.out.println(nameList.size());
}
// list 转成 已ID为key value 为 List<People> 对象的map
Map<String, List<People>> collect = list.stream().collect(Collectors.groupingBy(People::getId));
// list根据对象的某个属性去重
List<People> distinctItems = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(People::getId, item -> item, (item1, item2) -> item1),
map -> new ArrayList<>(map.values())))
// list 转成 已ID为key value 为 People 对象的map
Map<String, People> collct = List.stream()
.collect(Collectors.toMap(People::getId, people-> people));
// 取key不能为空,并且去重,相同则覆盖之后的值。 replacement ,项目不覆盖则取 existing
Map<String, BdmsDatainfoVo> map =bdmsList.stream().filter(item -> item.getCode() != null)
.collect(Collectors.toMap(
BdmsDatainfoVo::getCode, // keyMapper
Function.identity(), // valueMapper
(existing, replacement) -> replacement // mergeFunction
));
//排序
// 按照数量进行排序(正序)
goodsList = goodsList.stream().sorted(Comparator.comparing(Goods::getNum)).collect(Collectors.toList());
System.out.println("正序按照数量进行排序:" + JSON.toJSONString(goodsList));
// 按照数量进行排序(倒序)
goodsList = goodsList.stream().sorted(Comparator.comparing(Goods::getNum).reversed()).collect(Collectors.toList());
System.out.println("倒序按照数量进行排序:" + JSON.toJSONString(goodsList));
// 按金额进行倒序,金额相同就按照数量来进行正序
goodsList = goodsList.stream().sorted(Comparator.comparing(Goods::getPrice, Comparator.reverseOrder()).thenComparing(Goods::getNum)).collect(Collectors.toList());
//异步查询接口,提高接口查询性能问题
ExecutorService executor = new ThreadPoolExecutor(20, 20,
5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(100), new ThreadFactoryBuilder().setNameFormat("Risk-View-pool-%d").build());
/**
* 组装返回数据
* @param poList
* @return
*/
private List<RiskViewDataDto> assembleRiskViewData(Long projectId, List<ProjectFirstIndicatorPo> poList,
Map<Integer, ProjectFirstIndicatorContentPo> contentPo ,
Map<Long, List<ProjectSecondIndicatorPo>> indicatorPo){
List<CompletableFuture<RiskViewDataDto>> futures = poList.stream().map(item -> CompletableFuture.supplyAsync(() -> {
RiskViewDataDto riskViewDataDto = new RiskViewDataDto();
riskViewDataDto.setProjectIndicatorId(item.getId());
riskViewDataDto.setSourceId(item.getSourceId());
riskViewDataDto.setName(item.getName());
riskViewDataDto.setStrategy(item.getCompetitiveStrategy());
// 取二级指标数据
riskViewDataDto.setViewList(getSecondRiskViewList(projectId, result, item, indicatorPo));
return riskViewDataDto;
}, executor)).collect(Collectors.toList());
return futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
}
ExecutorService executorService = new ThreadPoolExecutor(10, 10,
5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(100), new ThreadFactoryBuilder().setNameFormat("indicator-risk-pool-%d").build());
private List<SecondRiskView> getSecondRiskViewList( Long projectId, Boolean result, ProjectFirstIndicatorPo po, Map<Long, List<ProjectSecondIndicatorPo>> indicatorPo){
List<SecondRiskView> riskViews = Lists.newArrayList();
List<ProjectSecondIndicatorPo> secondIndicatorPos = indicatorPo.get(po.getId());
if(secondIndicatorPos != null && secondIndicatorPos.size() > 0){
secondIndicatorPos.forEach( item -> {
SecondRiskView secondRiskView = new SecondRiskView();
secondRiskView.setProjectIndicatorId(item.getId());
secondRiskView.setSourceId(item.getSourceId());
secondRiskView.setName(item.getName());
secondRiskView.setStrategy(item.getCompetitiveStrategy());
BigDecimal curStageCompetitivenessValue = item.getCurStageCompetitivenessValue();
BigDecimal complianceValue = item.getCompetitivenessComplianceValue();
secondRiskView.setComplianceScore(result ? curStageCompetitivenessValue : complianceValue);
secondRiskView.setCompetitivenessScore(item.getProjectCoreCompetitorCompetitivenessScore());
secondRiskView.setBaseRequirement(item.getBaseRequirement());
// 魅点要求
CompletableFuture<List<String> > charmRequirement = CompletableFuture.supplyAsync(() -> {
return projectIndicatorViewMapper.findCharmRequirementDataList(projectId,item.getId());
},executorService);
//目标达成路径
CompletableFuture<List<String> > targetReachPath = CompletableFuture.supplyAsync(() -> {
return projectIndicatorViewMapper.findTargetReachPath(projectId,item.getSourceId());
},executorService);
// 风险数据列表
CompletableFuture<List<RiskDto> > riskList = CompletableFuture.supplyAsync(() -> {
return projectIndicatorViewMapper.findRiskDataList(projectId,item.getId());
},executorService);
// t_project_indicator_view 取该表的 风险 和 进展情况
CompletableFuture<ProjectIndicatorViewPo > projectIndicatorViewPo = CompletableFuture.supplyAsync(() -> {
return projectIndicatorViewMapper.findProjectIndicatorViewPo(projectId,item.getId());
},executorService);
CompletableFuture.allOf(charmRequirement,targetReachPath,riskList,projectIndicatorViewPo).join();
// 目标达成路径
try {
List<String> list = charmRequirement.get();
List<String> targetReachPathList = targetReachPath.get();
List<RiskDto> riskDtos = riskList.get();
ProjectIndicatorViewPo indicatorViewPo = projectIndicatorViewPo.get();
secondRiskView.setCharmRequirement(list);
secondRiskView.setTargetReachPath(targetReachPathList);
secondRiskView.setRiskDtoList(riskDtos);
if(indicatorViewPo != null ){
secondRiskView.setRisk(indicatorViewPo.getRisk());
secondRiskView.setContent(indicatorViewPo.getContent());
}
}catch ( Exception e){
log.error("项目风险试图列表并发查询,出现异常:{}",e);
throw new AppException("项目风险试图列表数据并发查询,出现异常");
}
riskViews.add(secondRiskView);
});
}
return riskViews;
}
}
结果:
bool:false
id=1:name=李红
id=1:name=诸葛亮:score =130
id=2:name=李逵:score =60
2
@Test void testAdd() { People p1 = new People(1,"李红", 50); People p2 = new People(2,"李逵", 20); People p3 = new People(1,"诸葛亮", 80); People p4 = new People(2,"李逵", 40); List<People> list = new ArrayList<People>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); Map<Integer, List<People>> listMap = list.stream().collect(Collectors.groupingBy(People::getId)); listMap.forEach((key,value)->{ log.info("key:"+ key); for (int i = 0; i < value.size() ; i++) { People people = value.get(i); log.info("id="+ people.getId() +":name="+ people.getName()); } }); }
import com.baomidou.mybatisplus.annotations.TableName; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * @description: 燃油车月报实体对象 * @since 2022-12-19 */ @Data @TableName("FV_INTERESTING_MONTH_REPORT") @Builder @NoArgsConstructor @AllArgsConstructor public class FvInterestingMonthReport implements Serializable { private static final long serialVersionUID = 1L; /** * id */ private Long id; /** * vin码 */ private String vin; /** * 年 */ private Integer year; /** * 月 */ private Integer month; /** * 拥有天数 */ private Integer ownerDays; /** * 本月驾驶天数 */ private Integer driveDays; /** * 里程排名 */ private Integer totalMileageRank; /** * 行驶总里程,单位:km */ private BigDecimal totalMileage; /** * 平均速度,单位:km/h */ private BigDecimal averageSpeed; /** * 启动次数 */ private Integer startUpSum; /** * 驾驶时长,单位:hh:mm:ss */ private Long driveTime; /** * 油耗排名 */ private Integer avgFuelCostRank; /** * 百公里油耗,单位:L/100km */ private BigDecimal avgFuelCost; /** * 车系代码 */ private String vehicleSeriesCode; /** * 车系名称 */ private String vehicleSeriesName; /** * 创建人 */ private String createBy; /** * 修改人 */ private String updateBy; /** * 创建时间 */ private Date createDate; /** * 修改时间 */ private Date updateDate; /** * 当月最早用车时间 */ private Long tripStartTime; /** * 当月最晚用车时间 */ private Long tripEndTime; /** * 当月刹车总次数 */ private int brakeSum; /** * 急加速总次数 */ private int rapidAcceleraSum; /** * 急减速总次数 */ private int rapidSlowDownSum; /** * 最大速度,单位:km/h */ private BigDecimal maxSpeed; /** *行程打分 */ private Double tripScore; }
lambda 用法:
//本季度拥有天数 int ownerDays = list.stream().mapToInt(FvInterestingMonthReport::getOwnerDays).sum(); //本季度驾驶天数 int driveDays = list.stream().mapToInt(FvInterestingMonthReport::getDriveDays).sum(); //总里程 double totalMileage = list.stream().mapToDouble(fvInterestingMonthReport -> fvInterestingMonthReport.getTotalMileage().doubleValue()).sum(); //驾驶时间 long driveTime = list.stream().mapToLong(FvInterestingMonthReport::getDriveTime).sum(); // 平均速度 double averageSpeed = getAverageSpeed(list); // 启动次数 int startUpSum = list.stream().mapToInt(FvInterestingMonthReport::getStartUpSum).sum(); //百公里油耗 double avgFuelCost =avgFuelCost(list); //最大速度 BigDecimal maxSpeed = list.stream().max(Comparator.comparing(FvInterestingMonthReport::getMaxSpeed)).get().getMaxSpeed(); //本季度最早用车时间 Long tripStartTime = list.stream().min(Comparator.comparing(FvInterestingMonthReport::getTripStartTime)).get().getTripStartTime(); // 本季度最晚用车时间 Long tripEndTime = list.stream().max(Comparator.comparing(FvInterestingMonthReport::getTripEndTime)).get().getTripEndTime(); // 当月刹车总次数 int brakeSum = list.stream().mapToInt(FvInterestingMonthReport::getBrakeSum).sum(); //当月急加速总次数 int rapidSum = list.stream().mapToInt(FvInterestingMonthReport::getRapidAcceleraSum).sum(); //当月急减速总次数 int downSum = list.stream().mapToInt(FvInterestingMonthReport::getRapidSlowDownSum).sum(); //行程平均分 double tripScore = avgTripScore(list); //车系代码 String vehicleSeriesCode = list.stream().filter(fvInterestingMonthReport -> Objects.nonNull(fvInterestingMonthReport.getVehicleSeriesCode())).collect(Collectors.toList()).get(0).getVehicleSeriesCode(); // 车系名称 String vehicleSeriesName = list.stream().filter(fvInterestingMonthReport -> Objects.nonNull(fvInterestingMonthReport.getVehicleSeriesName())).collect(Collectors.toList()).get(0).getVehicleSeriesName();
/** * 计算平均得分 * @param list * @return */ private double avgTripScore(List<FvInterestingMonthReport> list){ if (list.isEmpty()) { return 0; } double tripScore = list.stream().mapToDouble(FvInterestingMonthReport::getTripScore).sum(); return CalculateUtil.doubleDivide(tripScore,list.size(), 1); } /** * 计算平均油耗 * @param list * @return */ private double avgFuelCost(List<FvInterestingMonthReport> list){ if (list.isEmpty()) { return 0; } double totalAverageSpeed = list.stream().mapToDouble(fvInterestingMonthReport -> fvInterestingMonthReport.getAvgFuelCost().doubleValue()).sum(); return CalculateUtil.doubleDivide(totalAverageSpeed,list.size(), 1); } /** * 计算平均速度 * @param list * @return */ private double getAverageSpeed(List<FvInterestingMonthReport> list ) { List<FvInterestingMonthReport> collect = list.stream().filter(fvInterestingMonthReport -> Objects.nonNull(fvInterestingMonthReport.getAverageSpeed())).collect(Collectors.toList()); if (collect.isEmpty()) { return 0; } double totalAverageSpeed = collect.stream().mapToDouble(fvInterestingMonthReport -> fvInterestingMonthReport.getAverageSpeed().doubleValue()).sum(); return CalculateUtil.doubleDivide(totalAverageSpeed,collect.size(), 1); }
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; public class CalculateUtil { public CalculateUtil() { } public static double doubleAdd(int scale, double... dd) { BigDecimal result = BigDecimal.ZERO; double[] var3 = dd; int var4 = dd.length; for(int var5 = 0; var5 < var4; ++var5) { double n = var3[var5]; result = result.add(new BigDecimal(Double.toString(n))); } return result.setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static BigDecimal double2BigDecimal(int scale, double dd) { BigDecimal result = BigDecimal.ZERO; result = result.add(new BigDecimal(Double.toString(dd))); return result.setScale(scale, RoundingMode.HALF_EVEN); } public static double doubleAdd(double... dd) { BigDecimal result = BigDecimal.ZERO; double[] var2 = dd; int var3 = dd.length; for(int var4 = 0; var4 < var3; ++var4) { double n = var2[var4]; result = result.add(new BigDecimal(Double.toString(n))); } return result.doubleValue(); } public static double parseString2Double(String str, int scale) { BigDecimal result = BigDecimal.ZERO; BigDecimal value = new BigDecimal(str); result = result.add(value); return result.setScale(scale).doubleValue(); } public static double doubleAbs(double d, int scale) { BigDecimal result = BigDecimal.ZERO; if (d < 0.0D) { d = -d; } result = result.add(new BigDecimal(d)); return result.setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static double doubleAdd(int scale, RoundingMode mode, double... dd) { BigDecimal result = BigDecimal.ZERO; double[] var4 = dd; int var5 = dd.length; for(int var6 = 0; var6 < var5; ++var6) { double n = var4[var6]; result = result.add(new BigDecimal(Double.toString(n))); } return result.setScale(scale, mode).doubleValue(); } public static double doubleAdd(double d1, double d2) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); return bd1.add(bd2).doubleValue(); } public static double doubleAdd(double d1, double d2, int scale) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); return bd1.add(bd2).setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static double add(BigDecimal bd1, BigDecimal bd2, int scale) { return bd1.add(bd2).setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static double doubleAdd(double d1, double d2, int scale, RoundingMode mode) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); return bd1.add(bd2).setScale(scale, mode).doubleValue(); } public static double doubleSubtract(double d1, double d2) { return d1 != -2.0D && d1 != -1.0D ? (new BigDecimal(Double.toString(d1))).subtract(new BigDecimal(Double.toString(d2))).doubleValue() : d1; } public static double doubleSubtract(double d1, double d2, int scale) { BigDecimal b = (new BigDecimal(Double.toString(d1))).subtract(new BigDecimal(Double.toString(d2))); return b.setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static double doubleSubtract(double d1, double d2, int scale, RoundingMode mode) { BigDecimal b = (new BigDecimal(Double.toString(d1))).subtract(new BigDecimal(Double.toString(d2))); return b.setScale(scale, mode).doubleValue(); } public static double doubleSubtract(double d1, int scale, double... d2) { BigDecimal b = new BigDecimal(Double.toString(d1)); for(int i = 0; i < d2.length; ++i) { double d = d2[i]; b.subtract(new BigDecimal(d)); } return b.setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static double formatNubmer(double d1, int scale) { BigDecimal bd = new BigDecimal(Double.toString(d1)); return bd.setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static double formatNubmer(double d1, int scale, RoundingMode mode) { BigDecimal bd = new BigDecimal(Double.toString(d1)); return bd.setScale(scale, mode).doubleValue(); } public static BigDecimal formatNubmer(BigDecimal d1, int scale, RoundingMode mode) { return d1.setScale(scale, mode); } public static String formatNubmer(double d1, int scale, String formatter) { BigDecimal bd = new BigDecimal(Double.toString(d1)); double dd = bd.setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); DecimalFormat df = new DecimalFormat(formatter); return df.format(dd); } public static String formatNubmer(double d1, int scale, RoundingMode mode, String formatter) { BigDecimal bd = new BigDecimal(Double.toString(d1)); double dd = bd.setScale(scale, mode).doubleValue(); DecimalFormat df = new DecimalFormat(formatter); return df.format(dd); } public static String formatNumberWithString(String formatter, String value) { if (!StringUtils.isEmpty(value) && !"null".equals(value)) { if (StringUtils.isEmpty(formatter)) { formatter = "#,##0.00#"; } BigDecimal bd = new BigDecimal(value); DecimalFormat df = new DecimalFormat(formatter); String result = df.format(bd); return result; } else { return "0.00"; } } public static double doubleDivide(double d1, double d2) { if (d1 != -2.0D && d1 != -1.0D) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); return bd1.divide(bd2).doubleValue(); } else { return d1; } } public static double doubleDivide(double d1, double d2, int scale) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); BigDecimal bd3 = bd1.divide(bd2, 10, RoundingMode.HALF_EVEN); return bd3.setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static double doubleDivide(double d1, double d2, int scale, RoundingMode mode) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); BigDecimal bd3 = bd1.divide(bd2, 10, mode); return bd3.setScale(scale, mode).doubleValue(); } public static double doubleMultiply(double d1, double d2) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); return bd1.multiply(bd2).doubleValue(); } public static double doubleMultiply(double d1, double d2, int scale) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); return bd1.multiply(bd2).setScale(scale, RoundingMode.HALF_EVEN).doubleValue(); } public static long double2Long(double d) { BigDecimal bd1 = new BigDecimal(Double.toString(d)); return bd1.setScale(0, RoundingMode.HALF_EVEN).longValue(); } public static double doubleMultiply(double d1, double d2, int scale, RoundingMode mode) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); return bd1.multiply(bd2).setScale(scale, mode).doubleValue(); } public static String formatFourNumber(int number) { NumberFormat nf = new DecimalFormat("0000"); return nf.format((long)number); } public static boolean isDivisible(double d1, double d2) { return d1 % d2 == 0.0D; } public static String scaleNumber(double num) { BigDecimal decimal = (new BigDecimal(num)).setScale(2, 4); return decimal.toString(); } public static String getIntValue(double num) { BigDecimal decimal = (new BigDecimal(num)).setScale(0, 4); return decimal.intValue() + ""; } public static double doublePower(double num, int power, int scale) { BigDecimal decimal = new BigDecimal(num); decimal = decimal.pow(power); return decimal.setScale(scale, 4).doubleValue(); } public static String getPercent(BigDecimal b1, BigDecimal b2, int scale, RoundingMode mode, boolean fixedScale) { if (b1 != null && b2 != null && b2.compareTo(BigDecimal.ZERO) != 0) { NumberFormat format = getFormat(scale, mode, fixedScale); BigDecimal radio = b1.divide(b2, 10, mode); return format.format(radio); } else { return (scale > 0 ? "0." : "0") + StringUtils.rightPad("", scale, '0') + "%"; } } public static String getPercent(double b1, double b2, int scale, RoundingMode mode, boolean fixedScale) { return getPercent(NumberUtils.createBigDecimal(String.valueOf(b1)), NumberUtils.createBigDecimal(String.valueOf(b2)), scale, mode, fixedScale); } public static String getPercent(BigDecimal b1, BigDecimal b2) { return getPercent(b1, b2, 2, RoundingMode.HALF_UP, true); } public static String getPercent(double b1, double b2) { return getPercent(b1, b2, 2, RoundingMode.HALF_UP, true); } public static String getLavePercent(String... p) { return getLavePercent(2, RoundingMode.HALF_UP, true, p); } public static String getLavePercent(int scale, RoundingMode mode, boolean fixedScale, String... p) { List<BigDecimal> aList = new ArrayList(); String[] var5 = p; int var6 = p.length; for(int var7 = 0; var7 < var6; ++var7) { String s = var5[var7]; if (s.contains("%")) { aList.add((new BigDecimal(s.replaceAll("%", ""))).movePointLeft(2)); } else { aList.add(new BigDecimal(s)); } } BigDecimal lave = BigDecimal.ONE; BigDecimal b; for(Iterator var10 = aList.iterator(); var10.hasNext(); lave = lave.subtract(b)) { b = (BigDecimal)var10.next(); } return getPercent(lave, BigDecimal.ONE, scale, mode, fixedScale); } public static NumberFormat getFormat(int scale, RoundingMode mode, boolean fixedScale) { NumberFormat format = DecimalFormat.getPercentInstance(); format.setMaximumFractionDigits(scale); if (fixedScale) { format.setMinimumFractionDigits(scale); } format.setRoundingMode(mode); return format; } public static NumberFormat getFormat() { return getFormat(2, RoundingMode.HALF_UP, true); } public static String formatNumber(double number) { NumberFormat nf = new DecimalFormat("#,##0.00"); return nf.format(number); } public static String formatLastZero(double value) { String index_s = String.valueOf(value); if (index_s.substring(index_s.indexOf(".") + 1, index_s.length()).length() == 1) { index_s = index_s + "0"; } String r_str = ""; String str = index_s.substring(0, index_s.indexOf(".")); String index_one = index_s.substring(index_s.indexOf(".") + 1, index_s.indexOf(".") + 2); String index_two = index_s.substring(index_s.indexOf(".") + 2, index_s.indexOf(".") + 3); if (index_two.equals("0")) { if (index_one.equals("0")) { r_str = str; } else { r_str = str + "." + index_one; } } else if (!index_two.equals("0")) { r_str = index_s; } return r_str; } public static void main(String[] args) throws ParseException { System.out.println(formatNumber(0.0D)); } }
public class People {
private String id ;
private String name;
private Integer score;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public People(String id, String name, Integer score) {
super();
this.id = id;
this.name = name;
this.score = score;
}
}
Java集合List按日期升序或降序:
public class Gps { private String gs; private long gpsTime; private Boolean Result; public Gps(String gs,long gpsTime,Boolean Result){ this.gs=gs; this.gpsTime=gpsTime; this.Result=Result; }
List<Gps> list = new ArrayList<>(); Gps gps2 = new Gps("3",1650695209000L,false); list.add(gps2); Gps gps = new Gps("1",1650522409000L,true); list.add(gps); Gps gps1 = new Gps("4",1650781609000L,false); list.add(gps1); // 升序 list.sort(Comparator.comparing(Gps::getGpsTime)); //降序 // Collections.sort(list, Comparator.comparing(Gps::getGpsTime, (t1, t2) -> t2.compareTo(t1))); System.out.println("list.get(0):"+list.get(0).toString());
测试升序:
测试降序:
第二种写法:
List<Gps> listAgeAsc = list.stream().sorted( Comparator.comparing(Gps::getGpsTime)).collect(Collectors.toList()); System.out.println("Asc升序结果:" + listAgeAsc.toString()); List<Gps> listAgeDesc = list.stream().sorted( Comparator.comparing(Gps::getGpsTime).reversed()).collect(Collectors.toList()); System.out.println("Desc降序结果:" + listAgeDesc.toString());
经常碰到一个 前端穿了的需要新增 后端也需要删除
Long[] department = new Long[]{ 1l,6l,3l}; List<Long> longList = new ArrayList<>(Arrays.asList(department)); List<SysDeptUser> deptUsers = new ArrayList<>(); SysDeptUser sysDeptUser = new SysDeptUser(); sysDeptUser.setDeptId(2L); sysDeptUser.setUserId(3l); SysDeptUser sysDeptUser1 = new SysDeptUser(); sysDeptUser1.setDeptId(4L); sysDeptUser1.setUserId(4l); deptUsers.add(sysDeptUser1); deptUsers.add(sysDeptUser); List<Long> deptList = deptUsers.stream().map(e -> e.getDeptId()).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList()); List<Long> list =new ArrayList<>(); list.addAll(longList); // 先取出 交集 取的值是 2 longList.retainAll(deptList); // 取差集 需要新增到部门表 1 3 list.removeAll(longList); //取差集 需要删除部门表 4 deptList.removeAll(longList); System.out.println("list"+list.toString()); // System.out.println("longList"+longList.toString());// 2 System.out.println("deptList"+deptList.toString());
结果:
list[1, 6, 3]
longList[]
deptList[4, 2]