!416 CollUtil新增2个互换元素位置的静态方法

Merge pull request !416 from TanLongHui/v5-dev
This commit is contained in:
Looly 2021-09-17 11:54:44 +00:00 committed by Gitee
commit 2f57c2aaf9
2 changed files with 52 additions and 1 deletions

View File

@ -2954,4 +2954,34 @@ public class CollUtil {
return IterUtil.isEqualList(list1, list2);
}
/**
* 将指定元素交换到指定索引位置,其他元素的索引值不变
* 交换会修改原List
*
* @param list 列表
* @param element 需交换元素
* @param targetIndex 目标索引
*/
public static <T> void swapIndex(List<T> list, T element, Integer targetIndex) {
if (isEmpty(list) || !list.contains(element)) {
return;
}
Collections.swap(list, list.indexOf(element), targetIndex);
}
/**
* 将指定元素交换到指定元素位置,其他元素的索引值不变
* 交换会修改原List
*
* @param list 列表
* @param element 需交换元素
* @param targetElement 目标元素
*/
public static <T> void swapElement(List<T> list, T element, T targetElement) {
if (isEmpty(list) || !list.contains(targetElement)) {
return;
}
swapIndex(list, element, list.indexOf(targetElement));
}
}

View File

@ -767,9 +767,30 @@ public class CollUtilTest {
}
@Test
public void sortComparableTest(){
public void sortComparableTest() {
final List<String> of = ListUtil.toList("a", "c", "b");
final List<String> sort = CollUtil.sort(of, new ComparableComparator<>());
Assert.assertEquals("a,b,c", CollUtil.join(sort, ","));
}
@Test
public void swapIndex() {
List<Integer> list = Arrays.asList(7, 2, 8, 9);
CollUtil.swapIndex(list, 8, 1);
Assert.assertTrue(list.get(1) == 8);
}
@Test
public void swapElement() {
Map<String, String> map1 = new HashMap<>();
map1.put("1", "张三");
Map<String, String> map2 = new HashMap<>();
map2.put("2", "李四");
Map<String, String> map3 = new HashMap<>();
map3.put("3", "王五");
List<Map<String, String>> list = Arrays.asList(map1, map2, map3);
CollUtil.swapElement(list, map2, map3);
Map<String, String> map = list.get(2);
Assert.assertTrue(map.get("2").equals("李四"));
}
}