List对象集合的操作

List对象集合的操作

一、List集合

List list = new ArrayList();
list集合不能为空

  1. 去重

list = list.stream().distinct().collect(Collectors.toList());
List<ModelMapModelElement.Element> filterElementList = elementList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ModelMapModelElement.Element::getElementCode))), ArrayList::new));

  1. 排序

(1)升序排列

Collections.sort(list);

(2)倒序排列

Collections.reverse(list);

(3)自定义排序

Collections.sort(list, new Comparator()
{
public int compare(String a1, String a2)
{
int io1 = sortRule.indexOf(a1);
int io2 = sortRule.indexOf(a2);
return io1 - io2;
}
});

  1. List和数组互相转换

(1)数组转List

List resultList= new ArrayList<>(Arrays.asList(array));
JAVA9:List resultList = List.of(array);
String[] arrays = {“a”, “b”, “c”};
List listStrings = Stream.of(arrays).collect(Collectors.toList());

(2)List转数组

String[] strings = list.stream().toArray(String[]::new);

(3)字符串转List

list List list=Arrays.asList(strs);

(4)字符串转数组

String[] strArr = new String[]{strs};

  1. List去除空值-使用引用方式
List<String> llist= llist.stream().map(Student::getNo)
                .filter(StringUtils::isNotBlank).collect(Collectors.toList());

二、List 对象集合

List list = new ArrayList();
list集合不能为空

1. 获取所有的主键

List idList = list.stream().map(Student::getId).collect(Collectors.toList());

2. 排序

(1)升序排列,排序完不用再赋值

list .sort(comparing(Student::getScore));

> list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());

(2)倒序排列

list.sort(comparing(Student::getScore).reversed());

> list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());

(3)自定义排序
a、(“按照分数降序排序,当分数相同时, 按照身高降序排序”)

Collections.sort(students, new Comparator()
{
public int compare(Student student1, Student student2)
{
if(student1.getScore().equals(student2.getScore())){
return student2.getHeight() - student1.getHeight();
}else{
return student2.getScore() - student1.getScore();
}
}
});

b、(“使用年龄进行降序排序,年龄相同再使用身高升序排序”)

list.stream().sorted(Comparator.comparing(Student::getAge).reversed().thenComparing(Student::getHeight)).collect(Collectors.toList());

3. LIST转Map

(1)对象转map

Map<String,Student> maps = list.stream().collect(Collectors.toMap(Student::getId,Function.identity(),(key1,key2)->key2));

Map<String,Student> maps = StreamUtil.toMap(list, Student::getId);

(2)获取单一属性

Map<String,String> maps = list.stream().collect(Collectors.toMap(Student::getId,Student::getAge,(key1,key2)->key2));

    Map<String, String> map = StreamUtil.toMap(billList, Bill::getId, Bill::getBillNo);

    Set<String> billItemIds = StreamUtil.mapToSet(billItemList, BillItem::getId);

4. 中文排序

private Collator collator = Collator.getInstance(Locale.CHINA);
Integer sortType = 1;//名称正序
public void sort(List list) {
Collections.sort(list, new Comparator() {
@Override
public int compare(Studento1, Studento2) {
return sortByName(o1, o2);
}
});
}
private int sortByName(Studento1, Student o2) {
return sortType * collator.compare(o1.getName(), o2.getName());
}

5. 条件过滤

List newList = list.stream().filter(s -> s.getGener().equals(“男”)).collect(Collectors.toList());

6. List 以ID分组 Map<Integer,List>

Map<Integer, List> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

当key值为null的时候会报错,请使用先过滤,再分组
Map<String, List> listMap = elementQuantityList.stream().filter(x -> StringUtils.isNotBlank(x.getFormulaExpress())).collect(Collectors.groupingBy(ElementQuantityVO::getFormulaExpress));

过滤优化
//获取所有已挂接构件
Set hookComponentList = businessDataOutList.stream().map(BusinessDataOutVo::getRelatedObject).collect(Collectors.toSet());

    //过滤出需要的构件属性
    List<ComponentFixedProperties> filterFixedPropertiesList = fixedPropertiesList.stream().filter(s -> !hookComponentList.contains(s.getUuid())).collect(Collectors.toList());

7. 校验文件ID不能重复

List fileIdList = list.stream().collect(Collectors.groupingBy(AddCollectCondition::getFileId, Collectors.counting())) .entrySet().stream().filter(entry -> entry.getValue() >1).map(Map.Entry::getKey).collect(Collectors.toList());
if (fileIdList.size() > 0) {
throw new BimdcException(HttpStatus.BAD_REQUEST.value(), “收藏文件重复”);
}

8. 筛选出符合条件的项目

List ompProjectList = ompProjectInterfaceService.getOmpProjectList(null, null);
if (null != ompProjectList) {
OmpProject ompProject = ompProjectList.stream().filter(s -> (s.getCode().equals(projectCode) && s.getCompanyId().equals(companyId))).findAny().orElse(null);
}

9. 交集、并集、差集

List rowIdList = rowIdList01.stream().filter(item -> rowIdList02.contains(item)).collect(Collectors.toList());

import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;

public class Test {

public static void main(String[] args) {
    List<String> list1 = new ArrayList<String>();
    list1.add("1");
	list1.add("2");
	list1.add("3");
	list1.add("5");
	list1.add("6");

    List<String> list2 = new ArrayList<String>();
    list2.add("2");
	list2.add("3");
	list2.add("7");
	list2.add("8");

    // 交集
    List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
    System.out.println("---交集 intersection---");
    intersection.parallelStream().forEach(System.out :: println);

    // 差集 (list1 - list2)
    List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
    System.out.println("---差集 reduce1 (list1 - list2)---");
    reduce1.parallelStream().forEach(System.out :: println);

    // 差集 (list2 - list1)
    List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
    System.out.println("---差集 reduce2 (list2 - list1)---");
    reduce2.parallelStream().forEach(System.out :: println);

    // 并集
    List<String> listAll = list1.parallelStream().collect(toList());
    List<String> listAll2 = list2.parallelStream().collect(toList());
    listAll.addAll(listAll2);
    System.out.println("---并集 listAll---");
    listAll.parallelStream().forEachOrdered(System.out :: println);

    // 去重并集
    List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
    System.out.println("---得到去重并集 listAllDistinct---");
    listAllDistinct.parallelStream().forEachOrdered(System.out :: println);

    System.out.println("---原来的List1---");
    list1.parallelStream().forEachOrdered(System.out :: println);
    System.out.println("---原来的List2---");
    list2.parallelStream().forEachOrdered(System.out :: println);

}

}

10. 去除某一字段重复值

list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getModelFloorId()))), ArrayList::new));

11、遍历map集合

            for (Map.Entry<String, List<B>> entry : map.entrySet()) {
            	entry.getKey()
            }

12、遍历转换对象

    List<ItemDTO> dTOList = itemList.stream().map(item -> {
        ItemDTO dto= new ItemDTO();
        BeanUtil.copyProperties(item , dto, "id");
        dto.setItemId(item .getId());
        return dto;
    }).collect(Collectors.toList());

13、将List<String>中的元素拼接成字符串,逗号隔开

String name = modelService.listByCodes(carCodes).stream().map(Model::getName).collect(Collectors.joining(","));

String name = list.stream().map(String::valueOf).collect(Collectors.joining(","));
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值