您好,登錄后才能下訂單哦!
這篇文章主要介紹了JAVA8 STREAM COLLECT GROUPBY分組實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
實(shí)體類People,有個(gè)返回list的buildPeopleList方法,方便測(cè)試。
import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author: rhyme * @date: 2019-09-26 17:31 * @topic: "主題" * @description: "描述" */ @Data @NoArgsConstructor @AllArgsConstructor @Builder public class People { private String name; private String character; private String sex; private int age; public static People buildDefault() { return People.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build(); } public static List<People> buildPeopleList() { People p1 = People.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build(); People p2 = People.builder().name("Zhang").character("optimistic").sex("female").age(23).build(); People p3 = People.builder().name("Hu").character("shy").sex("female").age(25).build(); People p4 = People.builder().name("Y").character("Righteous").sex("male").age(24).build(); return new ArrayList<>(Arrays.asList(p1, p2, p3, p4)); } }
測(cè)試類GroupByTest,分別根據(jù)性別分組,統(tǒng)計(jì)各個(gè)性別人數(shù),以及各個(gè)性別映射姓名。
import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.stream.Collectors; /** * @author: rhyme * @date: 2019-10-14 15:59 * @topic: "主題" * @description: "描述" */ public class GroupByTest { private List<People> people; private BiConsumer soutKV; private Map result; @Before public void init() { people = People.buildPeopleList(); soutKV = (k, v) -> System.out.println(k + ":" + v); } @After public void soutResult() { if (!CollectionUtils.isEmpty(result)) { result.forEach(soutKV); } } /** * 根據(jù)性別分組 */ @Test public void groupBySex() { result = people.stream().collect( Collectors.groupingBy(People::getSex) ); } /** * 分別統(tǒng)計(jì)不同性別各自的人數(shù) */ @Test public void groupBySexCount() { result = people.stream().collect( Collectors.groupingBy(People::getSex, Collectors.counting() )); } /** * 分別統(tǒng)計(jì)不同性別各自的name列表 */ @Test public void groupBySexName() { result = people.stream().collect( Collectors.groupingBy( People::getSex, Collectors.mapping(People::getName, Collectors.toSet()) )); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。