@Data
class Person {
private String uuid;
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.uuid = UUID.randomUUID().toString();
this.name = name;
this.gender = gender;
this.age = age;
}
}
List<Person> persons = new ArrayList<>();
persons.add(new Person("张三", "男", 27));
persons.add(new Person("李四", "男", 14));
persons.add(new Person("王五", "女", 17));
persons.add(new Person("赵六", "女", 34));
Map<Boolean, List<Person>> personsByAge = persons.stream()
.collect(Collectors.partitioningBy(p -> p.getAge() > 18));
System.out.println(JSON.toJSONString(personsByAge));
Map<String, List<Person>> personByGender = persons.stream()
.collect(Collectors.groupingBy(Person::getGender));
System.out.println(JSON.toJSONString(personByGender));
Map<String, String> uuidNameMap = persons.stream()
.collect(Collectors.toMap(Person::getUuid, Person::getName));
System.out.println(JSON.toJSONString(uuidNameMap));
实际情况有可能同一个key会对应多个value,就有可能抛Duplicate key异常。这时可以传入第三个参数决定重复时如何选择,比如我们想构造<name, uuid>的映射,但是考虑可能有重名的可能,就可以这么做:
Map<String, String> nameUuidMap = persons.stream()
.collect(Collectors.toMap(Person::getName, Person::getUuid, (p1, p2) -> p1));
System.out.println(JSON.toJSONString(nameUuidMap));
这里(p1, p2) -> p1表示如果重复则取前者。
public class CollectionEach {
public static void main(String[] args) {
// 创建一个集合
Collection objs = new HashSet();
objs.add("C语言中文网Java教程");
objs.add("C语言中文网C语言教程");
objs.add("C语言中文网C++教程");
// 调用forEach()方法遍历集合
objs.forEach(obj -> System.out.println("迭代集合元素:" + obj));
}
}
List<BuyProduction> productions
List<Long> list = productions.stream().map(BuyProduction::getProductionId).collect(Collectors.toList());
import java.util.*;
public class Demo{
public static void main(String[] args){
ArrayList<Integer> my_arr = new ArrayList<Integer>();
my_arr.add(190);
my_arr.add(267);
my_arr.add(12);
my_arr.add(0);
System.out.println("排序之前,数组列表中的元素是 : " + my_arr);
Collections.sort(my_arr, (o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0);
System.out.println("排序后,数组列表中的元素是 : " + my_arr);
}
}
树形结构排序
import java.util.*;
public class Demo{
public static void main(String[] args){
TreeMap<Integer, String> my_treemap = new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0);
my_treemap.put(56, "Joe");
my_treemap.put(43, "Bill");
my_treemap.put(21, "Charolette");
my_treemap.put(33, "Jonas");
System.out.println("treemap包含以下元素: " + my_treemap);
}
}
其他排序
public class Demo01 {
public static void main(String[] args) {
// 定义字符串数组
String[] strArr = { "abc", "cd", "abce", "a" };
// 传统方法
// 匿名内部类
Arrays.sort(strArr, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s2.length(), s1.length());
}
});
// 输出排序结果
for (String s : strArr) {
System.out.println(s);
}
System.out.println("---------------------");
// Lambda表达式
Arrays.sort(strArr, (s1, s2) -> Integer.compare(s2.length(), s1.length()));
// 输出
for (String s : strArr) {
System.out.println(s);
}
常规遍历
for (Hero h : heros) {
if (h.hp > 100 && h.damage < 50)
System.out.println(h.name);
}
聚合遍历
heros
.stream()
.filter(h -> h.hp > 100 && h.damage < 50)
.forEach(h -> System.out.println(h.name));
filter 匹配
distinct 去除重复(根据equals判断)
sorted 自然排序
sorted(Comparator) 指定排序
limit 保留
skip 忽略
mapToDouble 转换为double的流
map 转换为任意类型的流
public class Hero implements Comparable<Hero>{
public String name;
public float hp;
public int damage;
public Hero(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getHp() {
return hp;
}
public void setHp(float hp) {
this.hp = hp;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public Hero(String name) {
this.name =name;
}
//初始化name,hp,damage的构造方法
public Hero(String name,float hp, int damage) {
this.name =name;
this.hp = hp;
this.damage = damage;
}
@Override
public int compareTo(Hero anotherHero) {
if(damage<anotherHero.damage)
return 1;
else
return -1;
}
@Override
public String toString() {
return "Hero [name=" + name + ", hp=" + hp + ", damage=" + damage + "]rn";
}
}
package lambda;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import charactor.Hero;
public class TestAggregate {
public static void main(String[] args) {
Random r = new Random();
List<Hero> heros = new ArrayList<Hero>();
for (int i = 0; i < 5; i++) {
heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100)));
}
//制造一个重复数据
heros.add(heros.get(0));
System.out.println("初始化集合后的数据 (最后一个数据重复):");
System.out.println(heros);
System.out.println("满足条件hp>100&&damage<50的数据");
heros
.stream()
.filter(h->h.hp>100&&h.damage<50)
.forEach(h->System.out.print(h));
System.out.println("去除重复的数据,去除标准是看equals");
heros
.stream()
.distinct()
.forEach(h->System.out.print(h));
System.out.println("按照血量排序");
heros
.stream()
.sorted((h1,h2)->h1.hp>=h2.hp?1:-1)
.forEach(h->System.out.print(h));
System.out.println("保留3个");
heros
.stream()
.limit(3)
.forEach(h->System.out.print(h));
System.out.println("忽略前3个");
heros
.stream()
.skip(3)
.forEach(h->System.out.print(h));
System.out.println("转换为double的Stream");
heros
.stream()
.mapToDouble(Hero::getHp)
.forEach(h->System.out.println(h));
System.out.println("转换任意类型的Stream");
heros
.stream()
.map((h)-> h.name + " - " + h.hp + " - " + h.damage)
.forEach(h->System.out.println(h));
}
}
forEach() 遍历每个元素
toArray() 转换为数组
min(Comparator) 取最小的元素
max(Comparator) 取最大的元素
count() 总数
findFirst() 第一个元素
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import charactor.Hero;
public class TestAggregate {
public static void main(String[] args) {
Random r = new Random();
List<Hero> heros = new ArrayList<Hero>();
for (int i = 0; i < 5; i++) {
heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100)));
}
System.out.println("遍历集合中的每个数据");
heros
.stream()
.forEach(h->System.out.print(h));
System.out.println("返回一个数组");
Object[] hs= heros
.stream()
.toArray();
System.out.println(Arrays.toString(hs));
System.out.println("返回伤害最低的那个英雄");
Hero minDamageHero =
heros
.stream()
.min((h1,h2)->h1.damage-h2.damage)
.get();
System.out.print(minDamageHero);
System.out.println("返回伤害最高的那个英雄");
Hero mxnDamageHero =
heros
.stream()
.max((h1,h2)->h1.damage-h2.damage)
.get();
System.out.print(mxnDamageHero);
System.out.println("流中数据的总数");
long count = heros
.stream()
.count();
System.out.println(count);
System.out.println("第一个英雄");
Hero firstHero =
heros
.stream()
.findFirst()
.get();
System.out.println(firstHero);
}
}