【JAVA8】map操作 & 删除元素的简单方法
JAVA8-删除元素
传统的,在JAVA中得MAP中删除元素,可以这样,假设有个MAP:
Map<Integer, String> map = new HashMap<>();
map.put(1, "value 1");
map.put(2, "value 2");
map.put(3, "value 3");
for(Iterator<Integer> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
Integer key = iterator.next();
if(key != 1) {
iterator.remove();
}
}
而在JAVA8中,可以这样了,更为简单:
// 根据map中得值去判断删除
map.values().removeIf(value -> !value.contains("1"));
// 根据key删除
map.keySet().removeIf(key -> key != 1);
//通过getkey()方法获得值去删除
map.entrySet().removeIf(entry -> entry.getKey() != 1);
MAP本身没办法用removeif,要通过keySet,EntrySet去调用removeif方法,再看源码:
/**
* 移除集合中满足给定条件的所有元素,错误或者运行时异常发生在迭代时或者把条件传递给调用者的时候。
*
* @implSpec
* 默认的实现贯穿了使用迭代器iterator的集合的所有元素。每一个匹配的元素都将被用Iterator接口中的
* remove()方法移除。如果集合的迭代器不支持移除,则在第一次匹配时就会抛出异常 UnsupportedOperationException
*
* @param filter 令元素移除成功的条件
* @return {@code true} 如果所有的元素都被移除
* @throws NullPointerException 如果有一个过滤器是空的
* @throws UnsupportedOperationException 如果元素不能被从该集合中移除。如果一个匹配元素不能被移除,
* 通常来说,它就不支持移除操作,这时可能抛出这个异常。
* @since 1.8
*/
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
也可以这样用:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
// 这里单独定义了过滤
Predicate<String> predicate = (s) -> s.equals("a");
// 过滤掉a的元素
list.removeIf(predicate);
System.out.println(list.toString());
}
-——————————
1.putIfAbsent
// 如果这个key不存在,就put进去
import java.util.HashMap;
import java.util.Map;
/**
* @author bincai, bincai@mobvoi.com
* @date Oct 08 , 2018
*/
public class Run {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1,"bincai");
for (int i = 0; i < 3; i++) {
map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));
}
}
输出:
val0
bincai
val2
2.computeIfAbsent、computeIfPresent、compute
⑴compute
对已经存在和未存在的key都进行操作。
⑵computeIfPresent
computeIfPresent 的方法,对 指定的 在map中已经存在的key的value进行操作。
统计单词sed和magna出现的次数:
public static void main(String[] args) {
Map<String, Integer> wordCounts = new ConcurrentHashMap<>(10);
String s =
"Lorem ipsum dolor sit amet consetetur iam nonumy sadipscing " +
" elitr, sed diam nonumy eirmod tempor invidunt ut erat sed " +
"labore et dolore magna dolor sit amet aliquyam erat sed diam";
wordCounts.put("sed", 0);
wordCounts.put("magna",0);
for (String t : s.split(" ")) {
wordCounts.computeIfPresent(t, (k, v) -> v + 1);
}
System.out.println(wordCounts);
}
⑶computeIfAbsent
computeIfAbsent 的方法,对 指定的 在map中未存在的key的value进行操作。
加入我们有几个学生需要根据男女分组:
public static void main(String[] args) {
//学生的集合
List<Student> students = new ArrayList<>();
students.add(new Student("张三","男",18));
students.add(new Student("李四","男",20));
students.add(new Student("韩梅梅","女",18));
students.add(new Student("小红","女",45));
//声明接收结果的 map
Map<String, List<Student>> resultMap = new HashMap<>();
for (Student student : students) {
List<Student> s = resultMap.computeIfAbsent(student.getSex(), k -> new ArrayList<>());
s.add(student);
}
System.out.println(resultMap);
}
3.remove
根据value移除
private static void testRemove(){
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 3; i++) {
map.putIfAbsent(i, "val" + i);
}
map.remove(0,"val1");
map.remove(2,"val2");
// 可见,key为2的被移除
map.forEach((id, val) -> System.out.println(val));
}
输出:
val0
val1
4.getOrDefault
取不到就取默认值
private static void testGetOrDefault(){
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 3; i++) {
map.putIfAbsent(i, "val" + i);
}
System.out.println(map.getOrDefault(1,"bincai"));
System.out.println(map.getOrDefault(10,"bincai"));
}
输出:
val1
bincai
5.getOrDefault
private static void testMerge(){
Map<Integer, String> map = new HashMap<>();
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9concat
}
输出:
val9
val9concat
6.遍历map
private static void bianlimap(){
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", 4);
map.put("key5", 5);
map.put("key5", 'h');
map.keySet().forEach(key -> System.out.println("map.get(" + key + ") = " + map.get(key)));
map.entrySet().iterator().forEachRemaining(item -> System.out.println("key:value=" + item.getKey() + ":" + item.getValue()));
// 推荐使用
map.entrySet().forEach(entry -> System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue()));
map.values().forEach(System.out::println); // 等价于map.values().forEach(value -> System.out.println(value));
map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
}
输出:
map.get(key1) = value1
map.get(key2) = value2
map.get(key5) = h
map.get(key3) = value3
map.get(key4) = 4
key:value=key1:value1
key:value=key2:value2
key:value=key5:h
key:value=key3:value3
key:value=key4:4
key:value = key1:value1
key:value = key2:value2
key:value = key5:h
key:value = key3:value3
key:value = key4:4
value1
value2
h
value3
4
key:value = key1:value1
key:value = key2:value2
key:value = key5:h
key:value = key3:value3
key:value = key4:4
还没有评论,来说两句吧...