如何使用Stream API处理对象数组的列表?

huangapple go评论87阅读模式
英文:

How to use Stream API with list of object array?

问题

你可以使用流(Stream)API来重写这个方法,将其变得更简洁和易读。下面是使用流API的示例代码:

public List<AddNewSchoolBean> getEmployeeList() {
    try {
        List<Object[]> empList = Dao.getEmpDetailsFromUserMst();

        return empList.stream()
            .map(obj -> AddNewSchoolBean.builder()
                .employeeId(obj[0].toString())
                .employeeName(obj[1].toString())
                .schoolName(obj[2].toString())
                .build())
            .collect(Collectors.toList());

    } catch (Exception e) {
        e.printStackTrace();
        return new ArrayList<>(); // 返回空列表或者处理错误的方式
    }
}

这段代码使用了流API中的map来将empList中的元素转换为AddNewSchoolBean对象,然后使用collect将它们收集到一个List中。这样可以减少循环和手动添加元素的代码,使代码更加简洁和易于维护。

英文:

i have this method given below... how can i change this method in stream api.

public List&lt;AddNewSchoolBean&gt; getEmployeeList() {

		List&lt;AddNewSchoolBean&gt; list = new ArrayList&lt;&gt;();

		try {
			List&lt;Object[]&gt; empList = null;

			empList = Dao.getEmpDetailsFromUserMst();

			if (empList.size() != 0) {
				for (Object[] obj : empList) {
					AddNewSchoolBean bean = AddNewSchoolBean.builder()
							.employeeId((obj[0]).toString())
							.employeeName((obj[1]).toString())
							.schoolName((obj[2]).toString())
							.build();
					list.add(bean);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

答案1

得分: 1

Assuming you want to internally use a java.util.Stream I would suggest first to polish/cleanup your code a bit.

  1. You don't need to split declaration and assignment of the empList variable.
  2. Move the conversion logic into a private method.
  3. The if check for size doesn't add anything.
public List<AddNewSchoolBean> getEmployeeList() {

    List<AddNewSchoolBean> list = new ArrayList<>();

    try {
        List<Object[]> empList = Dao.getEmpDetailsFromUserMst();
        for (Object[] obj : empList) {         
            AddNewSchoolBean bean = convert(obj);
            list.add(bean);        
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}

private AddNewSchoolBean convert(Object[] empArray) {
  return AddNewSchoolBean.builder()
                    .employeeId((empArray[0]).toString())
                    .employeeName((empArray[1]).toString())
                    .schoolName((empArray[2]).toString())
                    .build();
}

Now assuming you cannot change the Dao.getEmpDetailsFromUserMst(); you can use the stream() method on the List to convert it to a java.util.Stream. Then you can use map to convert the array into an object and finally collect to a list and return it.

public List<AddNewSchoolBean> getEmployeeList() {
        List<Object[]> empList = Dao.getEmpDetailsFromUserMst();
        return empList.stream()
                   .map(this::convert)
                   .toList();
}

This is assuming you are on JDK17 and you need of course the aforementioned convert method.

英文:

Assuming you want to internally use a java.util.Stream I would suggest first to polish/cleanup your code a bit.

  1. You don't need to split declaration and assignment of the empList variable
  2. Move the conversion logic into a private method.
  3. The if check for size doesn't add anything.
public List&lt;AddNewSchoolBean&gt; getEmployeeList() {

    List&lt;AddNewSchoolBean&gt; list = new ArrayList&lt;&gt;();

    try {
        List&lt;Object[]&gt; empList = Dao.getEmpDetailsFromUserMst();
        for (Object[] obj : empList) {         
            AddNewSchoolBean bean = convert(obj);
            list.add(bean);        
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}

private AddNewSchoolBean convert(Object[] empArray) {
  return AddNewSchoolBean.builder()
                    .employeeId((empArray[0]).toString())
                    .employeeName((empArray[1]).toString())
                    .schoolName((empArray[2]).toString())
                    .build();
}

Now assuming you cannot change the Dao.getEmpDetailsFromUserMst(); you can use the stream() method on the List to convert it to a java.util.Stream. Then you can use map to convert the array into an object and finally collect to a list and return it.

public List&lt;AddNewSchoolBean&gt; getEmployeeList() {
        List&lt;Object[]&gt; empList = Dao.getEmpDetailsFromUserMst();
        return empList.stream()
                   .map(this::convert)
                   .toList();
}

This is assuming you are on JDK17 and you need ofcourse the aforementioned convert method.

答案2

得分: 1

我认为清晰的方式是将其映射到AddNewSchoolBean,然后收集到List中:

public List<AddNewSchoolBean> getEmployeeList() {
    try {
        List<Object[]> empList = Dao.getEmpDetailsFromUserMst();

        return empList.stream()
                .map(this::createAddNewSchoolBean)
                .collect(Collectors.toList());

    } catch (Exception e) {
        e.printStackTrace();
    }
    return Collections.emptyList();
}

private AddNewSchoolBean createAddNewSchoolBean(Object[] obj) {
    return AddNewSchoolBean.builder()
            .employeeId(String.valueOf(obj[0]))
            .employeeName(String.valueOf(obj[1]))
            .schoolName(String.valueOf(obj[2]))
            .build();
}
英文:

I think the clean way is to map it to AddNewSchoolBean and then collect into List:

public List&lt;AddNewSchoolBean&gt; getEmployeeList() {
    try {
        List&lt;Object[]&gt; empList = Dao.getEmpDetailsFromUserMst();

        return empList.stream()
                .map(this::createAddNewSchoolBean)
                .collect(Collectors.toList());

    } catch (Exception e) {
        e.printStackTrace();
    }
    return Collections.emptyList();
}

private AddNewSchoolBean createAddNewSchoolBean(Object[] obj) {
    return AddNewSchoolBean.builder()
            .employeeId(String.valueOf(obj[0]))
            .employeeName(String.valueOf(obj[1]))
            .schoolName(String.valueOf(obj[2]))
            .build();
}

答案3

得分: 0

你可以简化成以下形式:

@SneakyThrows
public List<AddNewSchoolBean> getEmployeeList() {
    return emptyIfNull(Dao.getEmpDetailsFromUserMst())
            .stream()
            .map(AddNewSchoolBean::new)
            .toList();
}

public class AddNewSchoolBean {
    String employeeId;
    String employeeName;
    String schoolName;

    public AddNewSchoolBean(Object[] data) {
        this.employeeId = String.valueOf(data[0]);
        this.employeeName = String.valueOf(data[1]);
        this.schoolName = String.valueOf(data[2]);
    }
}

import lombok.SneakyThrows;
import static org.apache.commons.collections4.ListUtils.emptyIfNull;

在这个Lambda表达式中,你首先确保你的集合不是null,通过使用emptyIfNull(可以是空的,但不会抛出NPE),然后你通过构造函数将它映射到AddNewSchoolBean bean/entity。当然,如果你愿意,你也可以使用with,但这样看起来更清晰。最后,你将结果收集到List中。请注意,这是不可变的结果,如果你需要可变的结果,请使用.collect(Collectors.toList())

英文:

You can simplify even to this

@SneakyThrows
public List&lt;AddNewSchoolBean&gt; getEmployeeList() {
    return emptyIfNull(Dao.getEmpDetailsFromUserMst())
            .stream()
            .map(AddNewSchoolBean::new)
            .toList();
}

And your AddNewSchoolBean to have Object constructor

public class AddNewSchoolBean{
   String employeeId;
   String employeeName;
   String schoolName;

   public AddNewSchoolBean(Object[] data) {
       this.employeeId = String.valueOf(data[0]);
       this.employeeName = String.valueOf(data[1]);
       this.schoolName = String.valueOf(data[2]);
   }
}

Some additional imports required to make it simpler

import lombok.SneakyThrows;
import static org.apache.commons.collections4.ListUtils.emptyIfNull;

In this Lambda expression, you first make sure your collection is not null, by using emptyIfNull (can be empty, but doesn't throw NPE), and then you stream through collection and map it to AddNewSchoolBean bean/entity via constructor. You can of course use with if you wish, but this looks cleaner. And then in the end you collect to List. Pleas note this is Immutable result, if you need Mutable, use .collect(Collectors.toList())

huangapple
  • 本文由 发表于 2023年5月15日 13:44:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定