需求分析:
List<Long> tagsIds;
List<Long> attributesIds;
现在需要将这两个Long类型的集合进行组合,利用笛卡尔乘积的方式得到组合后的结果,并需要将得到的笛卡尔结果转换为Java中自定义的bean对象。 例如:
tagsIds=[1,2,3]; attributesIds=[4,5]
笛卡尔积结果为:[[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]]
最终转为Javabean对象为:[{tagsId=1,attributeId=4},{tagsId=2,attributeId=4},{tagsId=3,attributeId=4},{tagsId=1,attributeId=5},{tagsId=2,attributeId=5},{tagsId=3,attributeId=3}]
实现方式:
//List 笛卡尔乘积, 将List类型的ids转换成需要的对象
public static List<TagsAttributeDto> descartes(List<Long>... lists) {
List<Long> tempList = new ArrayList<>();
List<TagsAttributeDto> collect = new ArrayList<>();
for (List<Long> list : lists) {
if (tempList.isEmpty()) {
tempList = list;
} else {
//java8新特性,stream流
collect = tempList.stream().flatMap(item -> list.stream().map(item2 -> {
TagsAttributeDto tagsAttributeDto = new TagsAttributeDto();
tagsAttributeDto.setEntityAttributeId(item2);
tagsAttributeDto.setEntityTagsId(item);
return tagsAttributeDto;
})).collect(Collectors.toList());
}
}
return collect;
}
//需要的Javabean对象
public class TagsAttributeDto {
private Long entityTagsId;
private Long entityAttributeId;
}
List<Long> tagsIds = tagsList.stream().map(EntityTags::getId).collect(Collectors.toList());
List<Long> attributesIds = attributeList.stream().map(EntityAttribute::getId).collect(Collectors.toList());
//调用方法 得到需要的笛卡尔积后需要的对象
List<TagsAttributeDto> list=descartes(tagsIds,attributesIds);