明天讲一下Collection,以及Collection和Lamdba的联合
Collection包含
List(ArrayList,LinkedList)
Set(HashSet) --- SortedSet(TreeSet)
Queue (PriorityQueue)-----Deque(LinkedList,ArrayDeque)
Map (HashMap)--- SortedMap(TreeMap)(Map不属于Collection)
对于Iterable
boolean forEach(Cosumer<? super E> consumer);
对于Collection
boolean removeIf(Predicate<? super E> filter);
对于List
boolean replaceAll(UnaryOperator<? super E> operator);boolean sort(Comparator<? super E> comparator);public class Main { public static void main(String[] args) { List<BankAccount> bankAccountList = new ArrayList<>(); bankAccountList.forEach(System.out::println); bankAccountList.removeIf(bankAccount -> bankAccount.getBalance()>20); List<String> names = new ArrayList<>(); names.replaceAll(name->name.toUpperCase()); names.replaceAll(String::toUpperCase); bankAccountList.sort(Comparator.comparing(BankAccount::getBalance) .thenComparing(BankAccount::getId)); }}
对于Map
void forEach(BiConsumer<? super K, ? super V> consumer);Map<String,List<BankAccount>> map = new HashMap<>();map.put("test",bankAccountList);map.forEach((city,list)-> System.out.println(city+": "+list.size() +" account"));输入:test: 0 account
putIfAbsent办法,能够间接get后再间接调用add办法
Map<String, List<Person>> map = new HashMap<>();map.putIfAbsent("boston",new ArrayList<>());map.get("boston").add(new Person());
compute办法,返回的值为新值,同put办法相同,put办法返回的是旧值
computeIfAbsent办法,只有当key对应的value为空时才放入新值,并返回新值
computeIfPresent办法,只有当key对应的value为非空时才放入新值,并返回新值
V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) Map<String,String> map1 = new HashMap<>();String val= map1.put("test","3");System.out.println(val);val= map1.compute("test", (k,v) -> "v");System.out.println(val);val = map1.computeIfAbsent("test",k -> "s");System.out.println(val);val = map1.computeIfPresent("test",(k,v) -> "s1");System.out.println(val);输入nullvvs1
computeIfAbsent办法,能够间接获取到新值并间接设置,写法简便
Map<String, Map<String,Person>> map = new HashMap<>();map.computeIfAbsent("one",key -> new HashMap<String,Person>).put("two",john);Map<String, List<Person>> map = new HashMap<>();map.computeIfAbsent("one",key -> new ArrayList<Person>()).add(john);
merge办法,获取原有key对应的value,通过Function操作,设置该key的值,并返回新值
V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)//接下面的将test的value设置为s1 val =map1.merge("test","dd",(k,v)-> k+v);System.out.println(val);输入s1dd
或者循环两个map的值,将其内容合并
Map<String,List<BankAccount>> map2 = new HashMap<>();Map<String,List<BankAccount>> map3 = new HashMap<>();map3.forEach( (key,value) -> map2.merge(key, value, (existingBankList, newBankList)->{ existingBankList.addAll(newBankList); return existingBankList; }));