list toMap

环境是jdk8以上 使用lamdba表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class ListToMap {
public static void main(String[] args) {
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("The Fellowship of the Ring", 1954, "0395489318"));
bookList.add(new Book("The Two Towers", 1954, "0345339711"));
bookList.add(new Book("The Return of the King", 1955, "0618129111"));
Map<String,Book> bookMap=bookList.stream()
.collect(Collectors.toMap(Book::getName, Function.identity()));
System.out.println(bookMap);
}
}
class Book {
private String name;
private int releaseYear;
private String isbn;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getReleaseYear() {
return releaseYear;
}

public void setReleaseYear(int releaseYear) {
this.releaseYear = releaseYear;
}

public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

public Book(String name, int releaseYear, String isbn) {
this.name = name;
this.releaseYear = releaseYear;
this.isbn = isbn;
}

@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", releaseYear=" + releaseYear +
", isbn='" + isbn + '\'' +
'}';
}
}

以上代码输出

1
2
{The Return of the King=Book{name='The Return of the King', releaseYear=1955, isbn='0618129111'}, The Fellowship of the Ring=Book{name='The Fellowship of the Ring', releaseYear=1954, isbn='0395489318'}, The Two Towers=Book{name='The Two Towers', releaseYear=1954, isbn='0345339711'}}

解决key冲突

上面的例子运行得很好,但是如果有一个重复的key会发生什么呢?
抛出异常

1
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Book{name='The Return of the King', releaseYear=1955, isbn='0618129111'}

要解决这个问题,我们需要使用另一种toMap()方法,附加一个参数,mergeFunction:

1
2
3
4
5
6
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction) {
return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
}

代码如下

1
2
Map<String,Book> bookMap=bookList.stream()
.collect(Collectors.toMap(Book::getName, Function.identity(),(k,v)->k));

java自定义排序

List 接口sort方法 实现Comparator 接口进行排序

需要注意有可能抛出:Comparison method violates its general contract异常

保证实现接口 返回0 -1 1.
需要实现升序返回:-1 0 1
实现降序返回:1 0 -1

timesort