本示例主要以官方示例为主
Map集合的简单使用
public class MapTest {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("AA",20);
map.put("BA",30);
map.put("AB",60);
map.put("BC",50);
map.put("EA",70);
System.out.println("遍历:");
map.forEach((k,v)->System.out.println(k+"-->"+v));
Map result = map.entrySet().stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue,
LinkedHashMap::new));//有序集合
System.out.println("排序Key:"+result);
Map<String, Integer> result2 = new LinkedHashMap<>();
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(e -> result2.put(e.getKey(), e.getValue()));
System.out.println("排序value:"+result2);
long count = map.entrySet().stream().filter(entry -> (entry.getKey().contains("B"))).count();
System.out.println("统计指定值:"+count);
// 官方的示例:
//BiConsumer Example
BiConsumer<String,Integer> printKeyAndValue
= (key,value) -> System.out.println(key+"-"+value);
printKeyAndValue.accept("One",1);
printKeyAndValue.accept("Two",2);
System.out.println("##################");
//Java Hash-Map foreach supports BiConsumer
HashMap<String, Integer> dummyValues = new HashMap<>();
dummyValues.put("One", 1);
dummyValues.put("Two", 2);
dummyValues.put("Three", 3);
//forEach方法参数就是BiConsumer
dummyValues.forEach((key,value) -> System.out.println(key+"-"+value));
}
}