程序代码
public class AnswerApp {
public static void main(String[] args) {
List<String> names = Lists.newArrayList("Answer", "AnswerAIL", "AI", "Answer", "Answer@AI@CODER", "KOBE@IVERSION@JORDAN");
// 根据条件对集合元素进行过滤
List<String> collect1 = names.stream().filter(e -> e.equals("Answer")).collect(Collectors.toList());
System.out.println("根据条件对集合元素进行过滤...");
System.out.println("before ==> " + names);
System.out.println("after ==> " + collect1);
System.out.println();
// 集合元素去重
List<String> collect2 = names.stream().distinct().collect(Collectors.toList());
System.out.println("集合元素去重...");
System.out.println("before ==> " + names);
System.out.println("after ==> " + collect2);
System.out.println();
// 跳过集合中前 n 个元素
List<String> collect3 = names.stream().skip(2).collect(Collectors.toList());
System.out.println("跳过集合中前 n 个元素...");
System.out.println("before ==> " + names);
System.out.println("after ==> " + collect3);
System.out.println();
// 扁平化集合元素
List<String> collect4 = names.stream().flatMap(e -> Arrays.stream(e.split("@"))).collect(Collectors.toList());
System.out.println("扁平化集合元素...");
System.out.println("before ==> " + names);
System.out.println("after ==> " + collect4);
System.out.println();
// 对集合元素进行分组
Map<String, List<String>> collect5 = collect4.stream().collect(Collectors.groupingBy(e -> e));
System.out.println("对集合元素进行分组...");
System.out.println("before ==> " + names);
System.out.println("after ==> " + collect5);
System.out.println();
// 集合转字符串
String collect6 = names.stream().collect(Collectors.joining("#"));
System.out.println("集合转字符串...");
System.out.println("before ==> " + names);
System.out.println("after ==> " + collect6);
System.out.println();
// map
List<String> collect7 = names.stream().map(e -> MessageFormat.format("Prefix:{0}", e)).collect(Collectors.toList());
System.out.println("map...");
System.out.println("before ==> " + names);
System.out.println("after ==> " + collect7);
System.out.println();
// reduce
System.out.println("reduce...");
List<Integer> scores = com.google.common.collect.Lists.newArrayList(130, 150, 143, 108, 100, 80);
Optional<Integer> totalScore = scores.stream().reduce((x, y) -> x + y);
System.out.println("totalScore ==> " + totalScore.orElse(0));
Optional<Integer> maxScore = scores.stream().reduce(Integer::max);
System.out.println("maxScore ==> " + maxScore.orElse(0));
Optional<Integer> minScore = scores.stream().reduce(Integer::min);
System.out.println("minScore ==> " + minScore.orElse(0));
}
}
程序运行结果
根据条件对集合元素进行过滤...
before ==> [Answer, AnswerAIL, AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
after ==> [Answer, Answer]
集合元素去重...
before ==> [Answer, AnswerAIL, AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
after ==> [Answer, AnswerAIL, AI, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
跳过集合中前 n 个元素...
before ==> [Answer, AnswerAIL, AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
after ==> [AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
扁平化集合元素...
before ==> [Answer, AnswerAIL, AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
after ==> [Answer, AnswerAIL, AI, Answer, Answer, AI, CODER, KOBE, IVERSION, JORDAN]
对集合元素进行分组...
before ==> [Answer, AnswerAIL, AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
after ==> {CODER=[CODER], Answer=[Answer, Answer, Answer], JORDAN=[JORDAN], KOBE=[KOBE], AnswerAIL=[AnswerAIL], AI=[AI, AI], IVERSION=[IVERSION]}
集合转字符串...
before ==> [Answer, AnswerAIL, AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
after ==> Answer#AnswerAIL#AI#Answer#Answer@AI@CODER#KOBE@IVERSION@JORDAN
map...
before ==> [Answer, AnswerAIL, AI, Answer, Answer@AI@CODER, KOBE@IVERSION@JORDAN]
after ==> [Prefix:Answer, Prefix:AnswerAIL, Prefix:AI, Prefix:Answer, Prefix:Answer@AI@CODER, Prefix:KOBE@IVERSION@JORDAN]
reduce...
totalScore ==> 711
maxScore ==> 150
minScore ==> 80
list.stream().peek() 与 list.stream().map()区别: peek用来修改数据,map用来转换数据类型
匹配 ***Match
public class AnswerApp {
public static void main(String[] args) throws Exception {
List<String> names = Lists.newArrayList("Answer", "AnswerAIL", "AI", "Answer", "Answer@AI@CODER", "KOBE@IVERSION@JORDAN");
// 全部元素匹配
boolean allMatch = names.stream().allMatch(e -> e.startsWith("Ans"));
System.out.println("全部元素匹配...");
System.out.println(MessageFormat.format("allMatch result {0}", allMatch));
System.out.println();
// 部分元素匹配
boolean anyMatch = names.stream().anyMatch(e -> e.startsWith("Ans"));
System.out.println("部分元素匹配...");
System.out.println(MessageFormat.format("anyMatch result {0}", anyMatch));
System.out.println();
// 所有元素都不匹配
boolean noneMatch = names.stream().noneMatch(e -> e.startsWith("Ans"));
System.out.println("所有元素都不匹配...");
System.out.println(MessageFormat.format("noneMatch result {0}", noneMatch));
System.out.println();
}
}
程序运行结果
全部元素匹配...
allMatch result false
部分元素匹配...
anyMatch result true
所有元素都不匹配...
noneMatch result false
List<String> names = Lists.newArrayList("Answer", "AI", "BlackManba");
Map<String, String> nameMap = ImmutableMap.of("Answer", "A1", "AI", "A2", "BlackManba", "A3");
System.out.println(names.stream().reduce((x, y) -> x + "#" + y).orElse(""));
System.out.println(String.join("#", names));
System.out.println(names.stream().map(e -> nameMap.getOrDefault(e, "")).collect(Collectors.joining("#", "[", "]")));
程序运行输出
Answer#AI#BlackManba
Answer#AI#BlackManba
[A1#A2#A3]
排序sorted
public class AnswerApp {
public static void main(String[] args) {
List<Student> students = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
students.add(new Student().setStuNo((long) i).setStuName("Jaemon-" + i).setIndex(i));
}
// 使用该方式进行排序, Student 类必须实现 Comparable<Student> 接口(o.getStuName().compareTo(this.getStuName()))
List<Student> students1 = students.stream().sorted().collect(Collectors.toList());
System.out.println(students1);
System.out.println();
// 根据 index 进行升序排序
List<Student> students2 = students.stream().sorted(Comparator.comparingInt(Student::getIndex)).collect(Collectors.toList());
System.out.println(students2);
System.out.println();
// 根据 stuName 进行降序排序
List<Student> students3 = students.stream().sorted((p, q) -> q.getStuName().compareTo(p.getStuName())).collect(Collectors.toList());
System.out.println(students3);
System.out.println();
}
}
Student实体类
@Data
@Accessors(chain = true)
public class Student {
private Long stuNo;
private String stuName;
private int index;
}
reduce用法
List -> List<List> -> List
@Data
public class Pair {
private Long id;
private Long transactionId;
private String key;
private String value;
}
@Data
public class TxInfo {
private List<Pair > pairs;
}
List<Pair> pairs =
txInfos
.stream()
// 过滤掉pairs为空的
.filter(e -> e.getPairs() != null)
.map(e -> {
for (Pair pair : e.getPairs()) {
pair.setTxId(e.getId());
}
return e.getPairs();
})
// 合并pairs
.reduce((x, y) -> {
x.addAll(y);
return x;
})
.get();
max/min
public class App {
public static void main(String[] args) {
List<Report> list = new ArrayList<>();
list.add(new Report(6, "java"));
list.add(new Report(5, "springboot"));
list.add(new Report(7, "spring"));
list.add(new Report(9, "mysql"));
list.add(new Report(2, "mq"));
list.add(new Report(8, "redis"));
// 集合中seq字段值最大的对象对应的text
System.out.println(
"max seq text: " + list.stream().max(Comparator.comparingInt(Report::getSeq)).map(Report::getText).get()
);
// 集合中seq字段值最小的对象对应的text
System.out.println(
"min seq text: " + list.stream().min(Comparator.comparingInt(Report::getSeq)).map(Report::getText).get()
);
}
@NoArgsConstructor
@AllArgsConstructor
@Data
public static class Report {
private int seq;
private String text;
}
}
程序运行输出
max seq text: mysql
min seq text: mq
解决map key重复问题
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName, (oldValue, newValue) -> newValue));