天天看點

java8 流式處理(1)

1、把list集合轉換成Map

List

<OrgResponDetail>

oldDetails = new ArrayList();

Map<String,

OrgResponDetail

> map = oldDetails.stream()

.collect(

Collectors.toMap(temp -> temp.getId(), temp -> temp

));

Map<String,String> map = oldDetails.stream() .collect(Collectors.toMap(

OrgResponDetail::getId,OrgResponDetail::getParentId

));

2、把list轉換為list

List

<String>

detailIds = list.stream()

.map

(temp -> temp.getId()).collect(Collectors.toList());

//

filter方法裡的條件是作為篩選條件

List

<Scheduling>

resultList = list.stream()

.

filter

(

distinctByKey(temp -> temp.getOrgId())

).collect(Collectors.toList());

public static

<T>

Predicate

<T>

distinctByKey

(Function<? super T, Object> keyExtractor) {

Map<Object, Boolean> seen = new ConcurrentHashMap<>();

return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;

}

3、去重

distinct()

List

<String>

oldDetails = new ArrayList();

List

<String>

list = list.stream()

.distinct()

.collect(Collectors.toList());

4、排序

//根據orders升序

sorted方法

List itemVoList = list.stream()

.sorted(Comparator.comparing(DicGroupItemVo::getOrders))

.collect(Collectors.toList());