最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java使用Lambda表達(dá)式查找list集合中是否包含某值問(wèn)題

 更新時(shí)間:2023年06月01日 15:45:25   作者:張蛋腚  
Java使用Lambda表達(dá)式查找list集合中是否包含某值的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

使用Lambda表達(dá)式查找list集合中是否包含某值

for (String className : allClassName) {
				if (!classDetailList.stream().filter(o -> ToolUtil.equals(o.getClassName(), className)).findFirst().isPresent()) {
					classDetailList.add(new AftersaleStatisticDTO().setClassName(className));
				} 			}

lambda表達(dá)式對(duì)List的常見(jiàn)操作記錄

List轉(zhuǎn)Map

@Data
class Person {
    private String uuid;
    private String name;
    private String gender;
    private int age;
    public Person(String name, String gender, int age) {
        this.uuid = UUID.randomUUID().toString();
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
}
List<Person> persons = new ArrayList<>();
persons.add(new Person("張三", "男", 27));
persons.add(new Person("李四", "男", 14));
persons.add(new Person("王五", "女", 17));
persons.add(new Person("趙六", "女", 34));

分組

Map<Boolean, List<Person>> personsByAge = persons.stream()
?? ?.collect(Collectors.partitioningBy(p -> p.getAge() > 18));
System.out.println(JSON.toJSONString(personsByAge));
Map<String, List<Person>> personByGender = persons.stream()
?? ?.collect(Collectors.groupingBy(Person::getGender));
System.out.println(JSON.toJSONString(personByGender));

自定義Map

Map<String, String> uuidNameMap = persons.stream()
?? ?.collect(Collectors.toMap(Person::getUuid, Person::getName));
System.out.println(JSON.toJSONString(uuidNameMap));

實(shí)際情況有可能同一個(gè)key會(huì)對(duì)應(yīng)多個(gè)value,就有可能拋Duplicate key異常。這時(shí)可以傳入第三個(gè)參數(shù)決定重復(fù)時(shí)如何選擇,比如我們想構(gòu)造<name, uuid>的映射,但是考慮可能有重名的可能,就可以這么做:

Map<String, String> nameUuidMap = persons.stream()
?? ?.collect(Collectors.toMap(Person::getName, Person::getUuid, (p1, p2) -> p1));
System.out.println(JSON.toJSONString(nameUuidMap));

這里(p1, p2) -> p1表示如果重復(fù)則取前者。

常用循環(huán)

常規(guī)循環(huán)

public class CollectionEach {
? ? public static void main(String[] args) {
? ? ? ? // 創(chuàng)建一個(gè)集合
? ? ? ? Collection objs = new HashSet();
? ? ? ? objs.add("C語(yǔ)言中文網(wǎng)Java教程");
? ? ? ? objs.add("C語(yǔ)言中文網(wǎng)C語(yǔ)言教程");
? ? ? ? objs.add("C語(yǔ)言中文網(wǎng)C++教程");
? ? ? ? // 調(diào)用forEach()方法遍歷集合
? ? ? ? objs.forEach(obj -> System.out.println("迭代集合元素:" + obj));
? ? }
}

單屬性提取集合

List<BuyProduction> productions
List<Long> list = productions.stream().map(BuyProduction::getProductionId).collect(Collectors.toList());

排序

求最大值或最小值

class Stu{
? ? private String str;
? ? public Stu(String str) {
? ? ? ? this.str = str;
? ? }
? ? public void setStr(String str) {
? ? ? ? this.str = str;
? ? }
? ? public String getStr() {
? ? ? ? return str;
? ? }
}
public static void main(String[] args) {
? ? List<Stu> dateList = new ArrayList<>();
? ? dateList.add(new Stu("2022-02-15"));
? ? dateList.add(new Stu("2021-12-25"));
? ? dateList.add(new Stu("2024-02-15"));
? ? dateList.add(new Stu("2023-02-15"));
? ? Stu minStu = dateList.stream().min(Comparator.comparing(Stu::getStr)).get();
? ? Stu maxStu = dateList.stream().max(Comparator.comparing(Stu::getStr)).get();
? ? System.out.println("maxStu = " + maxStu.getStr());
? ? System.out.println("minStu = " + minStu.getStr());
}
import java.util.*;
public class Demo{
? ?public static void main(String[] args){
? ? ? ArrayList<Integer> my_arr = new ArrayList<Integer>();
? ? ? my_arr.add(190);
? ? ? my_arr.add(267);
? ? ? my_arr.add(12);
? ? ? my_arr.add(0);
? ? ? System.out.println("排序之前,數(shù)組列表中的元素是 : " + my_arr);
? ? ? Collections.sort(my_arr, (o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0);
? ? ? System.out.println("排序后,數(shù)組列表中的元素是 : " + my_arr);
? ?}
}

樹(shù)形結(jié)構(gòu)排序

import java.util.*;
public class Demo{
? ?public static void main(String[] args){
? ? ? TreeMap<Integer, String> my_treemap = new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ? -1 : ? ? ? (o1 < o2) ? 1 : 0);
? ? ? my_treemap.put(56, "Joe");
? ? ? my_treemap.put(43, "Bill");
? ? ? my_treemap.put(21, "Charolette");
? ? ? my_treemap.put(33, "Jonas");
? ? ? System.out.println("treemap包含以下元素: " + my_treemap);
? ?}
}

其他排序

public class Demo01 {
? ? public static void main(String[] args) {
? ? ? ? // 定義字符串?dāng)?shù)組
? ? ? ? String[] strArr = { "abc", "cd", "abce", "a" };
? ? ? ? // 傳統(tǒng)方法
? ? ? ? // 匿名內(nèi)部類
? ? ? ? Arrays.sort(strArr, new Comparator<String>() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public int compare(String s1, String s2) {
? ? ? ? ? ? ? ? return Integer.compare(s2.length(), s1.length());
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? // 輸出排序結(jié)果
? ? ? ? for (String s : strArr) {
? ? ? ? ? ? System.out.println(s);
? ? ? ? }
? ? ? ? System.out.println("---------------------");
? ? ? ? // Lambda表達(dá)式
? ? ? ? Arrays.sort(strArr, (s1, s2) -> Integer.compare(s2.length(), s1.length()));
? ? ? ? // 輸出
? ? ? ? for (String s : strArr) {
? ? ? ? ? ? System.out.println(s);
? ? ? ? }

遍歷

常規(guī)遍歷

for (Hero h : heros) {
? ?if (h.hp > 100 && h.damage < 50)
? ? ? System.out.println(h.name);
}

聚合遍歷

heros
? ? .stream()
? ? .filter(h -> h.hp > 100 && h.damage < 50)
? ? .forEach(h -> System.out.println(h.name));

對(duì)元素進(jìn)行篩選:

  • filter 匹配
  • distinct 去除重復(fù)(根據(jù)equals判斷)
  • sorted 自然排序
  • sorted(Comparator) 指定排序
  • limit 保留
  • skip 忽略

轉(zhuǎn)換為其他形式的流:

  • mapToDouble 轉(zhuǎn)換為double的流
  • map 轉(zhuǎn)換為任意類型的流
public class Hero implements Comparable<Hero>{
? ? public String name;
? ? public float hp;
? ? public int damage;
? ? public Hero(){
? ? }
? ? public String getName() {
? ? ? ? return name;
? ? }
? ? public void setName(String name) {
? ? ? ? this.name = name;
? ? }
? ? public float getHp() {
? ? ? ? return hp;
? ? }
? ? public void setHp(float hp) {
? ? ? ? this.hp = hp;
? ? }
? ? public int getDamage() {
? ? ? ? return damage;
? ? }
? ? public void setDamage(int damage) {
? ? ? ? this.damage = damage;
? ? }
? ? public Hero(String name) {
? ? ? ? this.name =name;
? ? }
? ? //初始化name,hp,damage的構(gòu)造方法
? ? public Hero(String name,float hp, int damage) {
? ? ? ? this.name =name;
? ? ? ? this.hp = hp;
? ? ? ? this.damage = damage;
? ? }
? ? @Override
? ? public int compareTo(Hero anotherHero) {
? ? ? ? if(damage<anotherHero.damage)
? ? ? ? ? ? return 1;?
? ? ? ? else
? ? ? ? ? ? return -1;
? ? }
? ? @Override
? ? public String toString() {
? ? ? ? return "Hero [name=" + name + ", hp=" + hp + ", damage=" + damage + "]rn";
? ? }
}
package lambda;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import charactor.Hero;
public class TestAggregate {
? ? public static void main(String[] args) {
? ? ? ? Random r = new Random();
? ? ? ? List<Hero> heros = new ArrayList<Hero>();
? ? ? ? for (int i = 0; i < 5; i++) {
? ? ? ? ? ? heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100)));
? ? ? ? }
? ? ? ? //制造一個(gè)重復(fù)數(shù)據(jù)
? ? ? ? heros.add(heros.get(0));
? ? ? ? System.out.println("初始化集合后的數(shù)據(jù) (最后一個(gè)數(shù)據(jù)重復(fù)):");
? ? ? ? System.out.println(heros);
? ? ? ? System.out.println("滿足條件hp>100&&damage<50的數(shù)據(jù)");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .filter(h->h.hp>100&&h.damage<50)
? ? ? ? ? ? .forEach(h->System.out.print(h));
? ? ? ? System.out.println("去除重復(fù)的數(shù)據(jù),去除標(biāo)準(zhǔn)是看equals");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .distinct()
? ? ? ? ? ? .forEach(h->System.out.print(h));
? ? ? ? System.out.println("按照血量排序");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .sorted((h1,h2)->h1.hp>=h2.hp?1:-1)
? ? ? ? ? ? .forEach(h->System.out.print(h));
? ? ? ? System.out.println("保留3個(gè)");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .limit(3)
? ? ? ? ? ? .forEach(h->System.out.print(h));
? ? ? ? System.out.println("忽略前3個(gè)");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .skip(3)
? ? ? ? ? ? .forEach(h->System.out.print(h));
? ? ? ? System.out.println("轉(zhuǎn)換為double的Stream");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .mapToDouble(Hero::getHp)
? ? ? ? ? ? .forEach(h->System.out.println(h));
? ? ? ? System.out.println("轉(zhuǎn)換任意類型的Stream");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .map((h)-> h.name + " - " + h.hp + " - " + h.damage)
? ? ? ? ? ? .forEach(h->System.out.println(h));
? ? }
}

結(jié)束操作

  • forEach() 遍歷每個(gè)元素
  • toArray() 轉(zhuǎn)換為數(shù)組
  • min(Comparator) 取最小的元素
  • max(Comparator) 取最大的元素
  • count() 總數(shù)
  • findFirst() 第一個(gè)元素
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import charactor.Hero;
public class TestAggregate {
? ? public static void main(String[] args) {
? ? ? ? Random r = new Random();
? ? ? ? List<Hero> heros = new ArrayList<Hero>();
? ? ? ? for (int i = 0; i < 5; i++) {
? ? ? ? ? ? heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100)));
? ? ? ? }
? ? ? ? System.out.println("遍歷集合中的每個(gè)數(shù)據(jù)");
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .forEach(h->System.out.print(h));
? ? ? ? System.out.println("返回一個(gè)數(shù)組");
? ? ? ? Object[] hs= heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .toArray();
? ? ? ? System.out.println(Arrays.toString(hs));
? ? ? ? System.out.println("返回傷害最低的那個(gè)英雄");
? ? ? ? Hero minDamageHero =
? ? ? ? heros
? ? ? ? ? ? .stream()
? ? ? ? ? ? .min((h1,h2)->h1.damage-h2.damage)
? ? ? ? ? ? .get();
? ? ? ? System.out.print(minDamageHero);
? ? ? ? System.out.println("返回傷害最高的那個(gè)英雄");
? ? ? ? Hero mxnDamageHero =
? ? ? ? ? ? ? ? heros
? ? ? ? ? ? ? ? .stream()
? ? ? ? ? ? ? ? .max((h1,h2)->h1.damage-h2.damage)
? ? ? ? ? ? ? ? .get();
? ? ? ? System.out.print(mxnDamageHero); ? ??
? ? ? ? System.out.println("流中數(shù)據(jù)的總數(shù)");
? ? ? ? long count = heros
? ? ? ? ? ? ? ? .stream()
? ? ? ? ? ? ? ? .count();
? ? ? ? System.out.println(count);
? ? ? ? System.out.println("第一個(gè)英雄");
? ? ? ? Hero firstHero =
? ? ? ? ? ? ? ? heros
? ? ? ? ? ? ? ? .stream()
? ? ? ? ? ? ? ? .findFirst()
? ? ? ? ? ? ? ? .get();
? ? ? ? System.out.println(firstHero);
? ? }
}

去重

//按學(xué)生姓名去重
//可能會(huì)改變?cè)衛(wèi)ist的順序
List<Student> list = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
//直接去重
List<String> l = new ArryList();
List<String> list = l.stream().distinct().collect(Collectors.toList());

過(guò)濾

//按學(xué)生姓名過(guò)濾
List<Student> list = studentList.stream().filter(item -> "張三".equals(item.getName())).collect(Collectors.toList());

抽取

//按學(xué)生姓名抽取形成新對(duì)象Person
List<Person> personList = studentList.stream().map(s->{
?? ??? ??? ??? ??? ?Person person = new Person();
?? ??? ??? ??? ??? ?person .setName(s.getName());
?? ??? ??? ??? ??? ?return person ;
?? ??? ??? ??? ?}).collect(Collectors.toList());
//按學(xué)生id抽取形成map集合
Map<Long, Person> personMap = studentList.stream().collect(Collectors.toMap(s -> s.getId(), s -> s));
//按學(xué)生id抽取形成map集合,取第一個(gè)
Map<Long, Person> personMap = studentList.stream().collect(Collectors.toMap(s -> s.getId(), s -> s,(first,last)->first));
//按學(xué)生id抽取形成set集合
Set<Long> idSet = studentList.stream().map(s-> s.getId()).collect(Collectors.toSet());

計(jì)數(shù)

Map<String, Long> map = students.stream().collect(Collectors.groupingBy(Student::getName, Collectors.counting()));

最值

//最小
Integer min = studentList.stream().map(Student::getAge).min(Student::compareTo).get();
//最大
Integer max = studentList.stream().map(Student::getAge).max(Student::compareTo).get();
// 最大對(duì)象
User max = userList.stream().max(Comparator.comparing(Student::getAge)).get();
// 最小對(duì)象
User min = userList.stream().min(Comparator.comparing(Student::getAge)).get();

匹配

//查找list中是否都是張三
boolean result = studentList.stream().allMatch((s) -> s.getName().equals("張三"));
//查找list中是否有一個(gè)是張三
boolean result = studentList.stream().anyMatch((s) -> s.getName().equals("張三"));
//判斷l(xiāng)ist中沒(méi)有張三
boolean result = studentList.stream().noneMatch((s) -> s.getName().equals("張三"));

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 使用EasyPoi輕松導(dǎo)入導(dǎo)出Excel文檔的方法示例

    使用EasyPoi輕松導(dǎo)入導(dǎo)出Excel文檔的方法示例

    這篇文章主要介紹了使用EasyPoi輕松導(dǎo)入導(dǎo)出Excel文檔的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • Java實(shí)現(xiàn)從Html文本中提取純文本的方法

    Java實(shí)現(xiàn)從Html文本中提取純文本的方法

    今天小編就為大家分享一篇Java實(shí)現(xiàn)從Html文本中提取純文本的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • Java 使用 OPC UA的步驟詳解

    Java 使用 OPC UA的步驟詳解

    使用Java與OPC UA (OPC Unified Architecture) 進(jìn)行通信,可以使用開(kāi)源的Eclipse Milo庫(kù),下面給大家介紹使用Eclipse Milo庫(kù)與OPC UA服務(wù)器進(jìn)行交互的步驟,感興趣的朋友跟隨小編一起看看吧
    2026-01-01
  • java使用定時(shí)器實(shí)現(xiàn)監(jiān)聽(tīng)數(shù)據(jù)變化

    java使用定時(shí)器實(shí)現(xiàn)監(jiān)聽(tīng)數(shù)據(jù)變化

    這篇文章主要為大家詳細(xì)介紹了Java如何使用定時(shí)器監(jiān)聽(tīng)數(shù)據(jù)變化,當(dāng)滿足某個(gè)條件時(shí)(例如沒(méi)有數(shù)據(jù)更新)自動(dòng)執(zhí)行某項(xiàng)任務(wù),有興趣的可以了解下
    2023-11-11
  • 淺談String、StringBuffer和StringBuilder之間的區(qū)別

    淺談String、StringBuffer和StringBuilder之間的區(qū)別

    這篇文章主要介紹了淺談String、StringBuffer和StringBuilder之間的區(qū)別,通過(guò)字面量方式為字符串賦值時(shí),此時(shí)的字符串存儲(chǔ)在方法區(qū)的字符串常量池中,需要的朋友可以參考下
    2023-10-10
  • Springboot如何根據(jù)實(shí)體類生成數(shù)據(jù)庫(kù)表

    Springboot如何根據(jù)實(shí)體類生成數(shù)據(jù)庫(kù)表

    這篇文章主要介紹了Springboot如何根據(jù)實(shí)體類生成數(shù)據(jù)庫(kù)表的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Spring Security登錄接口兼容JSON格式登錄實(shí)現(xiàn)示例

    Spring Security登錄接口兼容JSON格式登錄實(shí)現(xiàn)示例

    前后端分離中,前端和后端的數(shù)據(jù)交互通常是JSON格式,本文主要介紹了Spring Security登錄接口兼容JSON格式登錄實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-01-01
  • Spring中@Conditional注解用法詳解

    Spring中@Conditional注解用法詳解

    這篇文章主要介紹了Spring中@Conditional注解用法詳解,@Conditional是Spring4版本新提供的一種注解,它的作用是按照設(shè)定的條件進(jìn)行判斷,把滿足判斷條件的bean注冊(cè)到Spring容器,需要的朋友可以參考下
    2023-11-11
  • SpringBoot整合POI導(dǎo)出通用Excel的方法示例

    SpringBoot整合POI導(dǎo)出通用Excel的方法示例

    這篇文章主要介紹了SpringBoot整合POI導(dǎo)出通用Excel的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Java中RedisUtils工具類的使用

    Java中RedisUtils工具類的使用

    本文主要介紹了Java中RedisUtils工具類的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07

最新評(píng)論

威信县| 观塘区| 平顶山市| 舞钢市| 太保市| 海晏县| 秭归县| 许昌县| 灵台县| 昭平县| 盐城市| 吉安县| 南木林县| 北辰区| 咸丰县| 广昌县| 淮南市| 贵德县| 新余市| 罗定市| 札达县| 鄱阳县| 北流市| 定州市| 承德县| 永靖县| 江孜县| 龙门县| 陆丰市| 罗田县| 景德镇市| 龙南县| 余江县| 邵武市| 姜堰市| 章丘市| 江华| 兴化市| 仙居县| 星座| 德保县|