list集合去重和排序

Jdk8对集合按照元素的属性进行排序

    Collections.sort(listJdk7,(s1,s2) ->s1.compareTo(s2));

 

根据元素属性,进行去重操作,不过这个会进行排序

List<Person> unique = persons.stream().collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new) );

 

如果不想排序,只是单纯去重,则可以:

HashMap<String,SchoolServiceModel>schoolServiceListUniqueMap=new HashMap<>();

schoolServiceModels.forEach(mo->{

if(!schoolServiceListUniqueMap.containsKey(mo.getDisplayAppName())){

schoolServiceListUniqueMap.put(mo.getDisplayAppName(),mo);

}

});

List<SchoolServiceModel> schoolServiceListUnique = schoolServiceListUniqueMap.values().stream()

.collect(Collectors.toList());

 

list的集合转数组:

List<String>strList=newArrayList<String>();

 

strList.add("aa");

 

strList.add("bb");

 

Object[]objs=strList.toArray();

 

String [] strs = (String[])strList.toArray(new String[0]);

 

注意:如果toArray中不传大小,则会报错

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

猜你喜欢

转载自blog.csdn.net/qq_39839828/article/details/109671279