JAVA8新方法(也不新啦,我们老啦)

就记录在这吧,虽然这个名字叫JAVA8新方法,但是实际上JAVA8一点也不新啦,主要是我们老了
list的removeIf方法

List list1 = Arrays.asList("one","two","three","four","five","six","seven");
List list2 = new ArrayList<>(list1);
//删除
boolean result = list2.removeIf(s -> s.length() > 4);
System.out.println(result);
System.out.println(list2.stream().collect(Collectors.joining(",")));
//输出
true
one,two,four,five,six
//替换
list2.replaceAll(s->s.toUpperCase());
System.out.println(list2.stream().collect(Collectors.joining(",")));
//输出
ONE,TWO,FOUR,FIVE,SIX
//排序
list2.sort(Comparator.naturalOrder());
System.out.println(list2.stream().collect(Collectors.joining(",")));
//输出
FIVE,FOUR,ONE,SIX,TWO

比较

Comparator comparator = Comparator.comparing(Person::getName).thenComparing(Person::getAge);
//反向比较
Comparator comparatorReversed = comparator.reversed();
//默认字母顺序
Comparator comparator1 = Comparator.naturalOrder();
//先按空后再按照字母顺序
Comparator comparator2 = Comparator.nullsFirst(Comparator.naturalOrder());
//先按照字母顺序,最后排空
Comparator comparator3 = Comparator.nullsLast(Comparator.naturalOrder());
//比较
Long max = Long.max(1L,2L);

BinaryOperator sum = (s1,s2) -> s1 + s2;
sum = Long::sum;

hashCode

Long l = 2234324234234324L;
int hash = l.hashCode();
System.out.println(hash);
hash = Long.hashCode(l);
System.out.println(hash);
//输出
642554319
642554319

Map forEach,getOrDefault,putIfAbsent

Map map =new HashMap<>();
map.put("key","value");
map.forEach((key,value)-> System.out.println(key+" "+value));
//输出
key value
//getOrDefault
Person deafulPerson = new Person();
deafulPerson.setName("Test");
Person p = (Person) map.getOrDefault("p",deafulPerson);
System.out.println(p.getName());
//输出
Test

Person p1 = new Person();
p1.setName("Test11");
//putIfAbsent
map.putIfAbsent("p", p);
System.out.println("putIfAbsent=="+map.get("p"));
//替换key为p的值为p1
map.replace("p", p1);
System.out.println("replace=="+map.get("p"));
//替换key值为p的为defaultPeron
map.replace("p", p1,deafulPerson);
System.out.println("replaceNew=="+map.get("p"));
//lambda替换
map.replaceAll((key,oldPerson) -> p1);
System.out.println("replaceAll=="+map.get("p"));
//输出
putIfAbsent==Person{name='Test', age=0}
replace==Person{name='Test11', age=0}
replaceNew==Person{name='Test', age=0}
replaceAll==Person{name='Test11', age=0}

你可能感兴趣的:(java8jdk8java)