我有两个vavr列表:
string query = "SELECT * FROM MyTable WHERE Date > @Delta";
DynamicParameters dp = new DynamicParameters();
dp.Add("@Delta", deltaDt, DbType.DateTime);
IEnumerable<object> records = connection.Query<object>(query, dp);
如何将List<Object> list1 = List.of("one", "two", "three", "for");
List<Object> list2 = List.of("one", "two", List.of("three", "for"));
转换为等于list2
?
编辑
我试图解释更多我想达到的目标:
list1
输出:
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
我想展平list1: List(one, two, three, for)
list2: List(one, two, List(three, for))
中的所有内部列表,因此展平的列表应等于list2
:
list1
应返回:
System.out.println("flattened: " + flattened);
System.out.println(list1.equals(flattened));
答案 0 :(得分:5)
您可以将Stream
与flatMap
一起使用:
List<Object> flattened =
list2.stream()
.flatMap(e -> ((e instanceof List) ? ((List<Object>)e).stream() : Stream.of(e)))
.collect(Collectors.toList());
System.out.println(flattened);
System.out.println(list1.equals(flattened));
输出:
[one, two, three, four]
true
编辑:
由于OP使用的是不同的List
,因此以下是io.vavr.collection.List
的类似解决方案:
List<Object> flattened =
list2.toStream()
.flatMap(e -> ((e instanceof List) ? ((List<Object>)e).toStream() : Stream.of(e)))
.collect(List.collector());
答案 1 :(得分:1)
使用Vavr,您不需要JDK的所有流/收集样板:
List<Object> result = list2.flatMap(o -> o instanceof List ? ((List) o) : List.of(o));