Lambda表達式集合操作

1、sort排序
根據某個對象字段屬性來排序對象
@Test
public void whenSortingEntitiesByName_thenCorrectlySorted() {
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
 
humans.sort((Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}

反轉排序
@Test
public void whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), new Human("Jack", 12));
    Comparator<Human> comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
 
    humans.sort(comparator.reversed());
    Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}


2、獲取某個對象集合中其中一個屬性的集合

List<Long> goodsIds = list.stream().map(CartListItemVO::getGoodsId).collect(Collectors.toList());

解釋:list:爲操作對象集合;
getGoodsId:要獲取的字段屬性


3、根據對象集合中某個屬性去掉對象集合中重複對象

List<VO> buildSeriesModels = list.stream()
                
.collect(Collectors.collectingAndThen(
                
        Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(VO::getId))),
                        ArrayList::new));

4、字符串截取轉list(將字符串按#分割並轉爲list)

List<Long> seriesIds = Arrays.asList(seriesId.split("#")).stream().map(s -> Long.parseLong(s.trim()))
                   
 .collect(Collectors.toList());

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章