java8關於list的操作


list操作

List轉Map

Map<String, String> collect = list.stream().collect(Collectors.toMap(p -> p.getId(), p -> p.getName()));

從 List 中取出某個屬性的組成 list 集合

//1.提取出list對象中的一個屬性
List<String> stIdList1 = stuList.stream().map(Person::getId).collect(Collectors.toList());

//2.提取出list對象中的一個屬性並去重
List<String> stIdList2 = stuList.stream().map(Person::getId).distinct().collect(Collectors.toList());

filter()過濾列表

List<Person> filterList = persons.stream().filter(p -> p.getSex().equals(1)).collect(Collectors.toList());

去除List中重復的String

List unique = list.stream().distinct().collect(Collectors.toList());

去除List中重復的對象

// Person 對象
public class Person {
    private String id;
    
    private String name;
    
    private String sex;

    <!--省略 get set-->
}
// 根據name去重
List<Person> unique = persons.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);
// 根據name,sex兩個屬性去重
List<Person> unique = persons.stream().collect(
           Collectors. collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
);

 

 

感謝

https://blog.csdn.net/ianly123/article/details/82658622

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM