java8流式編程拼接數組/List中對象的某個屬性值

1.場景需求

有一個list<Object>,需要將每個對象的一個屬性(key)對應的值(value)使用一個符號(*@#¥%_-)拼接起來,那麼就可以使用這種方式

代碼:

package com.study.three;

import com.alibaba.fastjson.JSONArray;

import java.util.*;
import java.util.stream.Collectors;

public class three {
    public static void main(String[] args) {
        List<Apple> list = new ArrayList<>();
        for (int i=0 ; i<10; i++){
            Apple apple = new Apple();
            apple.setName("蘋果"+i);
            apple.setWeight("重量"+i);
            apple.setColor("顏色"+i);
            list.add(apple);
        }
        //Map  appleList = new HashMap<String,Object>();
        //appleList.put("list",list);
        //ArrayList<Apple> list1 =(ArrayList<Apple>)appleList.get("list");
        String str =list.stream().map(n -> n.getName()).collect(Collectors.joining("_"));
        System.out.println(str);  //打印:蘋果0_蘋果1_蘋果2_蘋果3_蘋果4_蘋果5_蘋果6_蘋果7_蘋果8_蘋果9

    }
}

 升級版,過濾後再拼接

package com.study.three;

import com.alibaba.fastjson.JSONArray;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class three {
    public static void main(String[] args) {
        List<Apple> list = new ArrayList<>();
        for (int i=0 ; i<10; i++){
            Apple apple = new Apple();
            apple.setName("蘋果"+i);
            apple.setWeight("重量"+i);
            apple.setColor("顏色"+i);
            list.add(apple);
        }
        //Map  appleList = new HashMap<String,Object>();
        //appleList.put("list",list);
        //ArrayList<Apple> list1 =(ArrayList<Apple>)appleList.get("list");
        String str = list.stream().filter(n -> n.getName().equals("蘋果0")||n.getName().equals("蘋果1")).map(n -> n.getName()).collect(Collectors.joining("_"));
        System.out.println(str);  //打印:蘋果0_蘋果1

    }
}

 

 

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