我使用循环实现了这个,但我不知道如何使用流来实现。我们得到两个列表,例如 1 2 3 和 4 5 6,混合后结果将是 1 4 2 5 3 6。
public <T> List<T> mixingList(List<T> list1, List<T> list2) {
List<T> result = new ArrayList<>();
int maxSize = list1.size() > list2.size() ? list1.size() : list2.size();
for (int i = 0; i < maxSize; i++) {
if (i < list1.size()) {
result.add(list1.get(i));
}
if (i < list2.size()) {
result.add(list2.get(i));
}
}
return result;
}
我为此准备测试。首先有 3 个测试 - 第二个列表大小相同 - 第三个是一个空列表 - 大小不同
@Test
public void shouldReturnShakedList() {
//given
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 3, 5));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 4, 6));
//when
List<Integer> results = new ShakeListUtil().mixingList(list1, list2);
//then
Assertions.assertThat(results).containsExactly(1, 2, 3, 4, 5, 6);
Assertions.assertThat(results).hasSize(6);
}
@Test
public void shouldReturnJustList2IfList1IsEmpty() {
//given
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 4, 6));
//when
List<Integer> results = new ShakeListUtil().mixingList(list1, list2);
//then
Assertions.assertThat(results).containsExactly(2, 4, 6);
Assertions.assertThat(results).hasSize(3);
}
@Test
public void shouldReturnShakedListIfTheSizeListIsDifferent() {
//given
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 3));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 4, 6));
//when
List<Integer> results = new ShakeListUtil().mixingList(list1, list2);
//then
Assertions.assertThat(results).containsExactly(1, 2, 3, 4, 6);
Assertions.assertThat(results).hasSize(5);
}
知道如何在 Java 流上做到这一点吗?
米琪卡哇伊
胡子哥哥
暮色呼如
相关分类