gpt4 book ai didi

java - 根据合并标准有效地合并列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:56:55 27 4
gpt4 key购买 nike

我有三个已排序的列表,我想将它们合并为一个以从逗号分隔的字符串派生的特定顺序。这三个列表如下所示:

List<Square> squares;
List<Ball> balls;
List<Triangle> triangles;

现在我想将所有这些列表合并到 shapes 列表中,其中 Shape 是父类添加到这个列表不会破坏任何东西。

List<Shape> shapes

每个列表都按每个列表类型对象的 id 排序。合并顺序基于此字符串提供的顺序(我愿意接受更好的表示,因为这是 super hacky):

String mergeOrder = "Ball, Triangle, Squares"

基于上面的合并顺序,我想按照上面的顺序从每个列表中取出一个形状并添加到形状列表中,直到其中一个列表用完对象。此时,合并顺序应继续处理剩余的列表。即:

Balls List:
12
16
20

Triangles List:
1

Squares List:
9
10

Merged List:
12 -> Ball
1 -> Triangle
9 -> Square
16 -> Ball
10 -> Square (Triangles ran out)
20 -> Ball (Squares ran out)

执行此类合并过程的最佳方法是什么?任何代码片段/骨架都会有很大帮助!

最佳答案

这是一个示例代码

public class Main {

private static class Shape {

private final String value;

private final String type;

public Shape(String type, String value) {
this.type = type;
this.value = value;
}

@Override
public String toString() {
return type + "[" + value + "]";
}
}

public static void main(String[] args) {
List<Shape> balls = new ArrayList<>();
List<Shape> triangles = new ArrayList<>();
List<Shape> squares = new ArrayList<>();
balls.add(new Shape("Ball", "10"));
balls.add(new Shape("Ball", "12"));
balls.add(new Shape("Ball", "16"));
triangles.add(new Shape("Triangle", "1"));
squares.add(new Shape("Square", "4"));
squares.add(new Shape("Square", "5"));

List<Iterator<Shape>> shapes = new ArrayList<>();
shapes.add(balls.iterator());
shapes.add(triangles.iterator());
shapes.add(squares.iterator());

List<Shape> merged = new ArrayList<>();

boolean finished = false;
while (!finished) {
boolean hasNext = false;
for (Iterator<Shape> iterator : shapes) {
hasNext = hasNext || iterator.hasNext();
if (iterator.hasNext()) {
merged.add(iterator.next());
}
}
finished = !hasNext;
}

System.out.println(merged);

}
}

更新:

流迭代:

  boolean finished = false;
while (!finished) {
List<Iterator<Shape>> iteratorsWithNext = shapes.stream().filter(
s -> s.hasNext()).collect(Collectors.toList());
iteratorsWithNext.forEach(it -> merged.add(it.next()));
finished = iteratorsWithNext.isEmpty();
}

输出

[Ball[10], Triangle[1], Square[4], Ball[12], Square[5], Ball[16]]

关于java - 根据合并标准有效地合并列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33573752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com