使用循环算法从多个列表中选择数据的有效方法 [英] Efficient way to choose data from several Lists with round robin algorithm

查看:54
本文介绍了使用循环算法从多个列表中选择数据的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从几个列表中,我需要使用循环算法选择数据,以创建一个包含所有其他值的单个结果列表.

From several lists I need to create a single result list with the values of all of the others, by choosing the data with a round robin algorithm.

list1 = val1_1,val1_2 .. 
list2 = val2_1,val2_2 .. 
list3 = val3_1,val3_2 ..
//rr choosing
result = val1_1,val2_1,val3_1,val1_2,val2_2,val3_2,val1_3...

每个列表中的值数可能不同.我该怎么办?

The number of values in each list may be different. How can I do this?

推荐答案

您可以使用从各个列表派生的 Iterators Queue .从队列中获取下一个迭代器,从迭代器中获取下一个元素,如果不为空,则将其添加回队列中.

You could use a Queue of Iterators derived from the individual lists. Get the next iterator from the queue, get the next element from the iterator, and add it back to the queue if it is not empty.

List<String> lst1 = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> lst2 = new ArrayList<>(Arrays.asList("A", "B"));
List<String> lst3 = new ArrayList<>(Arrays.asList("1", "2", "3", "4"));

Queue<Iterator<String>> iters = new LinkedList<>(Stream.of(lst1, lst2, lst3)
        .map(List::iterator).collect(Collectors.toList()));

List<String> result = new LinkedList<>();
while (! iters.isEmpty()) {
    Iterator<String> iter = iters.poll();
    if (iter.hasNext()) {
        result.add(iter.next());
        iters.add(iter);
    }
}
System.out.println(result); // [a, A, 1, b, B, 2, c, 3, 4]

这篇关于使用循环算法从多个列表中选择数据的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆