java 8从对象列表

时间:2017-05-11 17:08:02

标签: java-8

这是问题的扩展。我有一个消息列表。我想创建一个包含审计值的自定义消息列表。

list of id from a list of age using java 8

public class Messages {

int id;
String message;
int audId;
String audmessage;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public int getAudId() {
    return audId;
}

public void setAudId(int audId) {
    this.audId = audId;
}

public String getAudmessage() {
    return audmessage;
}

public void setAudmessage(String audmessage) {
    this.audmessage = audmessage;
}

public Messages(int id, String message, int audId, String audmessage) {

    this.id = id;
    this.message = message;
    this.audId = audId;
    this.audmessage = audmessage;
  }
}


public class CustomMessage {

int id;
String msg;
List<Aud> list;
//getters and setters
 }

public class Aud {

int id;
int message;
   //getters and setters
 }


  public class Demo {

    public static  void main(String args[]){
      List<Messages> list = new ArrayList<Messages>();
      list.add(new Messages(1,"abc",10,"a1"));
      list.add(new Messages(2,"ac",21,"a2"));
      list.add(new Messages(3,"adc",31,"a3"));
      list.add(new Messages(4,"aec",40,"a4"));
      list.add(new Messages(1,"abc",11,"a5"));
      list.add(new Messages(2,"ac",22,"a5"));
     }

预期输出为1,abc-&gt;审核清单为(10,a1),(11,a5);

1 个答案:

答案 0 :(得分:1)

这里的答案(如果我理解正确的话)几乎与上一个问题中的答案相同,只有几个假设。首先,您的<Project> <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" /> <PropertyGroup> <TargetFramework>net46</TargetFramework> </PropertyGroup> <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" /> <!-- add your custom targets after Sdk.targets is imported --> <Target Name="BeforeBuild"> <Message Text="Should run before build" Importance="High" /> </Target> <Target Name="AfterBuild"> <Message Text="Should run after build" Importance="High" /> </Target> </Project> 构造函数实际存在,如下所示:

Aud

没有<{em> public Aud(int id, String message) { this.id = id; this.message = message; } Holder,因此我使用了id and message

AbstractMap.SimpleEntry

修改

 Map<SimpleEntry<Integer, String>, List<Aud>> map = list.stream()
            .collect(Collectors.groupingBy(
                 m -> new SimpleEntry<>(m.getId(), m.getMessage()),
                 Collectors.mapping(
                       m -> new Aud(m.getAudId(), m.getAudMessage()), 
                       Collectors.toList())));

我不知道List<CustomMessage> l = list.stream() .collect(Collectors.groupingBy(m -> new SimpleEntry<>(m.getId(), m.getMessage()), Collectors.mapping(m -> new Aud(m.getAudId(), m.getAudMessage()), Collectors.toList()))) .entrySet() .stream() .map(e -> new CustomMessage(e.getKey().getKey(), e.getKey().getValue(), e.getValue())) .collect(Collectors.toList()); 应该是什么意思。

如果你使用的是setter和getter,你可以替换它:

want to check for null using optional

with:

 m -> new Aud(m.getAudId(), m.getAudMessage())