List 集合流操作基础

People 定义

People{

    Long id

    }

List 取属性值作为新List元素

List<Long> ids= peoples.stream()  //stream是内存操作 
.map(People::getId)   //取Id作为新List元素 
.collect(Collectors.toList());  //成型,输出people的id

//案例2 
List<Integer> list1=new ArrayList<Integer>();
 list1.add(1);
 list1.add(2);
 list1.add(3);
 List<String> list2=list1.stream()
    .map(Integer->Integer.toString()+"pppp")
        .collect(Collectors.toList()); //输出1ppp、2ppp、3ppp

//案例三
List<Long> ids = items.stream() 
    .map(item -> item.getId()).collect(Collectors.toList()); 
//将ids转换为String
String idsStr = ids.stream().map(String::valueOf).collect(Collectors.joining(", ", "[", "]"));

List 对象类型整个操作

//Class 转 JSON 
List<net.sf.json.JSONObject> jsonPeoples=peoples.stream()  
    .map(o -> net.sf.json.JSONObject.fromObject(o)).collect(Collectors.toList());

List 条件过滤

List<People> peoplesAndIdIsNotNull= peoples.stream()   
     .filter((People people) -> people.getId() !=                     
          null).collect(Collectors.toList());

List转换为Map

Map<Long, People> idPeopleMaps = peoples.stream()     
     .collect(Collectors.toMap(People::getId, o -> o));    

 //案例2(groupingBy,根据id分类)
 Map<Long, List<People>> idPeopleMaps= peoples.stream()            
     .collect(Collectors.groupingBy(People::getId));

Map单个元素转List<Map>

//创建id与people的映射idPeopleMap
Map<Long,People> idPeopleMap = new  HashMap(){{
                    put(1,people1);
                    put(2,people2);
                    put(3,people3);
                }};
//想得到这种效果
[
    {"id":1,"people":people1},
    {"id":2,"people":people2},
    {"id":3,"people":people3}
]

//操作
List<Map> list = idPeopleMap.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())    
    .map(item -> new HashMap() {{   
         put("no", item.getKey()); 
         put("res", item.getValue());  
     }}) 
.collect(Collectors.toList());

List  anyMatch

//判断peoples所有id有任一符合条件即返回true,否则返回false
peoples.stream().anyMatch(item -> item.getId().equals(89757L))

 

 

 

我见青山多妩媚 

料青山见我应如是

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值