CollUtil参照Map.putIfAbsent,新增集合的addIfAbsent方法

This commit is contained in:
青韵 2022-08-10 22:34:04 +08:00
parent 0fdec254ed
commit f77fd600a3
2 changed files with 65 additions and 0 deletions

View File

@ -2075,6 +2075,32 @@ public class CollUtil {
return IterUtil.toMap(null == values ? null : values.iterator(), map, keyFunc, valueFunc);
}
/**
* 一个对象不为空且不存在于该集合中时加入到该集合中<br>
* <pre>
* null, null => false
* [], null => false
* null, "123" => false
* ["123"], "123" => false
* [], "123" => true
* ["456"], "123" => true
* [Animal{"name": "jack"}], Dog{"name": "jack"} => true
* </pre>
* @param collection 被加入的集合
* @param object 要添加到集合的对象
* @param <T> 集合元素类型
* @param <S> 要添加的元素类型为集合元素类型的类型或子类型
* @return 是否添加成功
* @author Cloud-Style
*/
public static <T, S extends T> boolean addIfAbsent(Collection<T> collection, S object) {
if (object == null || collection == null || collection.contains(object)) {
return false;
}
return collection.add(object);
}
/**
* 将指定对象全部加入到集合中<br>
* 提供的对象如果为集合类型会自动转换为目标元素类型<br>

View File

@ -7,6 +7,9 @@ import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.junit.Assert;
import org.junit.Test;
@ -745,6 +748,24 @@ public class CollUtilTest {
Assert.assertEquals("d", map.get("keyd"));
}
@Test
public void addIfAbsentTest() {
// 为false的情况
Assert.assertFalse(CollUtil.addIfAbsent(null, null));
Assert.assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList(), null));
Assert.assertFalse(CollUtil.addIfAbsent(null, "123"));
Assert.assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList("123"), "123"));
Assert.assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)),
new Animal("jack", 20)));
// 正常情况
Assert.assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList("456"), "123"));
Assert.assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)),
new Dog("jack", 20)));
Assert.assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)),
new Animal("tom", 20)));
}
@Test
public void mapToMapTest(){
final HashMap<String, String> oldMap = new HashMap<>();
@ -951,4 +972,22 @@ public class CollUtilTest {
private String gender;
private Integer id;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
static class Animal {
private String name;
private Integer age;
}
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@Data
static class Dog extends Animal {
public Dog(String name, Integer age) {
super(name, age);
}
}
}