JAVA基础之Collection的Lambda

今天讲一下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 consumer);

对于Collection

boolean removeIf(Predicate filter);

对于List

boolean replaceAll(UnaryOperator operator);
boolean sort(Comparator comparator);

public class Main {
    public static void main(String[] args) {
        List bankAccountList = new ArrayList<>();
        bankAccountList.forEach(System.out::println);
        bankAccountList.removeIf(bankAccount -> bankAccount.getBalance()>20);
        List 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 consumer);

Map> 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> 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 remappingFunction)
V computeIfAbsent(K key, Function mappingFunction) 
V computeIfPresent(K key, BiFunction remappingFunction) 
Map 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);
输出
null
v
v
s1

computeIfAbsent方法,可以直接获取到新值并直接设置,写法简便

Map> map = new HashMap<>();
map.computeIfAbsent("one",key -> new HashMap)
.put("two",john);

Map> map = new HashMap<>();
map.computeIfAbsent("one",key -> new ArrayList())
.add(john);

merge方法,获取原有key对应的value,通过Function操作,设置该key的值,并返回新值

V merge(K key, V value,
        BiFunction remappingFunction)
//接上面的将test的value设置为s1        
val =map1.merge("test","dd",(k,v)-> k+v);
System.out.println(val);
输出
s1dd

或者循环两个map的值,将其内容合并

Map> map2 = new HashMap<>();
Map> map3 = new HashMap<>();
map3.forEach(
        (key,value) ->
                map2.merge(key, value, (existingBankList, newBankList)->{
                    existingBankList.addAll(newBankList);
                    return existingBankList;
                })
);

你可能感兴趣的:(JAVA基础之Collection的Lambda)