简体   繁体   English

使用Java流将Java List转换为另一个

[英]Converting Java List to another using java streams

I have a class Test 我有一堂课

public class Test{
  String codes;
  String field 1;
  ....
  String field n;
}

I have a list of test objects 我有一个测试对象列表

List<Test> objects, code can be one or more with a comma separated
testObj1("A", "field1".."fieldn")
testObj2("B,C", ...)
testObj3("D,E,F", ....)
testObj4("G", ...)

Trying to convert this list1 to new list2 with each code A, B, C... to its own object by retaining the remaining fields. 尝试通过保留其余字段将此list1转换为新list2 ,每个代码A,B,C ...到其自己的对象。

List<Test>
testObj1("A", ....)
testObj2("B", ....)
testObj3("C", ....)

list1.stream().collect(Collectors.toList())

I achieved this using loops (Sudo code) but looking for better logic 我使用循环(Sudo代码)实现了这一点,但寻找更好的逻辑

for(loop thru list1){
  String[] codesArr = testObj1.codes.split(",");
  for (String code : codesArr) {
    //Create new Obj 
    Test obj = new Test(code, testObj1.copyotherfields);
    //Add obj to list2
  }
}

You can use Stream.map with flatMap as : 您可以将Stream.mapflatMap一起使用:

List<Test> finalList = list1.stream()
        .flatMap(e -> Arrays.stream(e.getCodes().split(","))
                .map(c -> new Test(c, e.getField1(), e.getFieldn())))
        .collect(Collectors.toList());

This assumes that your Test class would have a constructor similar to the following implementation: 这假设您的Test类将具有类似于以下实现的构造函数:

class Test {
    String codes;
    String field1;
    String fieldn;

    // would vary with the number of 'field's
    Test(String codes, String field1, String fieldn) {
        this.codes = codes;
        this.field1 = field1;
        this.fieldn = fieldn;
    }
    // getters and setters
}

You can simplify this to: 您可以将其简化为:

List<Test> copy = list.stream()
                      .map(e -> Arrays.stream(e.codes.split(""))            
                                      .map(c -> new Test(c, e.otherField))
                     .collect(Collectors.toList()))
                     .findAny().orElse(...);

Which will stream through the given list, then stream through the Array yielded from split() and map to a new Test object and collect it to a List . 这将流经给定列表,然后通过split()Array流并映射到新的Test对象并将其收集到List It retrieves it through findAny() , which returns an Optional<List<Test>> , so I would recommend using orElse to retrieve a default value. 它通过findAny()检索它,它返回一个Optional<List<Test>> ,因此我建议使用orElse来检索默认值。

You can use a map function and then flatMap it to be like so: 你可以使用map函数然后flatMap它就像这样:

List<String> testList = Arrays.asList("one,two,three,four", "five", "six", "seven", 
"eight, nine", "ten");

 List<String> reMappedList = testList.stream()
 .map(s -> {
     String[] array = s.split(",");
     return Arrays.asList(array);
 })
 .flatMap(List::stream)
 .collect(Collectors.toList());

 System.out.println(reMappedList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM