软件编程
位置:首页>> 软件编程>> java编程>> JAVA JDK8 List获取属性列表

JAVA JDK8 List获取属性列表

作者:Sam哥哥  发布时间:2023-04-12 04:32:42 

标签:java,jdk,list,属性

概述

JDK 1.8里,可以使用如下代码获取List元素对象中某个属性的列表。


package test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ListAttrTest {
 public static void main(String[] args) {
   List<Coupon> couponList = new ArrayList<>();
   Coupon coupon1 = new Coupon(1,100,"优惠券1");
   Coupon coupon2 = new Coupon(2,200,"优惠券2");
   Coupon coupon3 = new Coupon(3,300,"优惠券3");
   couponList.add(coupon1);
   couponList.add(coupon2);
   couponList.add(coupon3);
   List<Integer> resultList = couponList.stream().map(Coupon::getCouponId).collect(Collectors.toList());
   System.out.println(resultList);
 }
}

public class Coupon {
 private Integer couponId;
 private Integer price;
 private String name;
 public Coupon(Integer couponId, Integer price, String name) {
   this.couponId = couponId;
   this.price = price;
   this.name = name;
 }
 public Integer getCouponId() {
   return couponId;
 }
 public void setCouponId(Integer couponId) {
   this.couponId = couponId;
 }
 public Integer getPrice() {
   return price;
 }
 public void setPrice(Integer price) {
   this.price = price;
 }
 public String getName() {
   return name;
 }
 public void setName(String name) {
   this.name = name;
 }
}

打印结果如下:

[1, 2, 3]

来源:https://blog.csdn.net/linsongbin1/article/details/83933184

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com