猿问

通过将字符串(来自数组)分配为对象的参数之一,将其他参数保留为空,将字符串数组转换为对象列表

我有一个字符串数组


adrs[] = {

    "BD Jules Ferry",

    "Rue de Republique",

    "Avenue de Julin"};

我有一个名为“Address”的对象(为了简单起见,省略了 getter setter)


public class Address{


     adrsLine1 String;


     adrsLine2 String;


     adrsLine3 String;


     postalCode String;


}

我想通过将数组中的每个字符串分配为 的参数来将其转换adrs[]为。List<<Address>> addrsListadrsLine1Address

一旦转换后,我的每个地址对象addrsList就会像这样,

  • addrsList.get(0)将有 [BD Jules Ferry, null, null, null]

  • addrsList.get(1)将有 [Rue de Republique, null, null, null]

  • addrsList.get(2)将有 [Avenue de Julin, null, null, null]

我使用Java 8,目前,我用它for loop来实现这一点,Java 8中有没有捷径或更有效的方法?

示例代码:

private String[] AdrsArray = {"BD Jules Ferry", "Rue de Republique", "Avenue de Julin"};


List<Address> addrsList = new ArrayList<>();


for (String adrsLine : AdrsArray){

    Address address = new ReturnAddress();

    address.setAdrsLine1(adrsLine);

    addrsList.add(address);

输出:


Address address = addrsList.get(0); 

address.getAdrsLine1() //should have "BD Jules Ferry"

address.getAdrsLine2() //should have null

address.getAdrsLine3() //should have null

address.getAdrsPostalCode() //should have null


慕的地8271018
浏览 132回答 3
3回答

萧十郎

您可以使用streamsJava 8 中的 available 来简化您的代码,如下所示。List<Address> addrsList = Arrays.stream(adrs).map(adr -> {&nbsp; &nbsp; Address address = new ReturnAddress();&nbsp; &nbsp; address.setAdrsLine1(adr);&nbsp; &nbsp; return address;}).collect(Collectors.toList());

湖上湖

您可以使用流。我建议您在类中实现构造函数Address,例如Address(String adrsLine1) {&nbsp; this.adrsLine1 = adrsLine1;}然后你可以用这个简短的代码片段来做到这一点:List<Address> addrsList = Arrays.stream(adrs)&nbsp; &nbsp; .map(adr -> new Address(adr))&nbsp; &nbsp; .collect(Collectors.toCollection(ArrayList::new));如果您需要特定的列表类型,例如ArrayList,您应该使用Collectors.toCollection(ArrayList::new),否则(如果您可以接受任何列表类型)您可以直接使用Collectors.toList()。

呼如林

List<Address> addressList = Arrays.stream(AdrsArray)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Address::new)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());您必须向接受的 Address 类添加一个构造函数adrsLine1。public class Address{&nbsp; &nbsp; &nbsp;private String adrsLine1;&nbsp; &nbsp; &nbsp;private String adrsLine2;&nbsp; &nbsp; &nbsp;private String adrsLine3;&nbsp; &nbsp; &nbsp;private String postalCode;&nbsp; &nbsp; &nbsp;Address(String address1) {&nbsp; &nbsp; &nbsp; &nbsp;adrsLine1 = address1;&nbsp; &nbsp; &nbsp;}}
随时随地看视频慕课网APP

相关分类

Java
我要回答