一、Map集合遍历日常开发最常使用,简单总结五种方法差异。
①、Iterator+entrySet写法【推荐JDK8以下】,Map.Entry是Map接口的内部接口,获取迭代器,然后依次取出每个迭代器里面的Map.Entry
Iterator<Map.Entry<Integer,String>> iterator=map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer,String> entry=iterator1.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
②、Iterator+keyset写法【不推荐,只能获取key,然后通过key获取对应的value,重复计算】
Iterator<Integer> iterator=map.keySet().iterator();
while (iterator.hasNext()){
Integer key=iterator.next();
System.out.println(key);
System.out.println(map.get(key));
}
③、foreach遍历方式【JDK8以下推荐写法】
for(Map.Entry<Integer,String> entry:map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
};
④:lambda表达式遍历【JDK8推荐写法,简捷】
map.forEach((key,value)->{
System.out.println(key);
System.out.println(value);
});
⑤:stream流遍历Map【JDK8不推荐写法,重复计算】
map.entrySet().stream().forEach((Map.Entry<Integer, String> entry) -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
如果Map集合存在一些中间处理,可以过滤操作,使用流式遍历也很方便。
附【List和Map删除集合元素】,业务实现里面经常需要清理集合中的指定的对象,这里以List和Map为例介绍一下正常的删除方式。
JDK8以下写法,迭代器会动态感知集合的变化。
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
Iterator<Integer> integerIterator=list.iterator();
while(integerIterator.hasNext()){
Integer integer=integerIterator.next();
if(integer.equals(5)){
integerIterator.remove();
}
}
System.out.println(list);
JDK8及以上的写法,新增一个removeIf方法
list.removeIf(key ->key.equals(4));
Map的写法。
JDK1.8一下
Iterator<Map.Entry<String,String>> iterator=map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry=iterator.next();
if(entry.getKey().equals("2")){
iterator.remove();
}
}
JDK1.8及以上
map.keySet().removeIf(key -> key.equals("3"));
【附录 JAVA的ArrayList的遍历方式】
public static void main(String[] args) {
// 1、普通for循环遍历
List<String> list = getList();
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
// 2、迭代器遍历
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
// 3、增强for-each遍历,底层通过迭代器遍历实现,迭代器遍历提供容器统一遍历接口
for(String str:list){
System.out.println(str);
}
// 4、Lambda遍历
list.stream().forEach(str->{
System.out.println(str);
});
// 5、ListIterator迭代,前向迭代
ListIterator<String> listIterator = list.listIterator();
while(listIterator.hasNext()){
System.out.println(listIterator.next());
}
// 6、ListIterator迭代,反向迭代
while(listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
}
private static List<String> getList() {
List<String> list=new ArrayList<>();
list.add("Map");
list.add("HashMap");
list.add("LinkedHashMap");
list.add("TreeMap");
list.add("ConcurrentHashMap");
return list;
}
附录:开发中常用的各种类型List集合,util包下
import java.util.Collections;
// 1、空集合,底层自定义一个EmptyList实现,接口空list返回,不像new ArrayList分配不必要的内存空间
Collections.emptyList();
// 2、单值List,底层定义SingletonList,size为1
Collections.singletonList(new Object());
// 3、线程安全的List,底层定义SynchronizedList,方法定义通过synchronized代码实现线程安全,定义了一个SynchronizedCollection
Collections.synchronizedList(new ArrayList<>());
// 4、不可变List,不支持修改,定义一个UnmodifiableCollection,UnmodifiableList
Collections.unmodifiableList(new ArrayList<>());
List转换Map整理.
/**
* 转换Map,保存后者
* @return Map<String,Book>
*/
private static Map<String,Book> convertOldValueMap(){
List<Book> bookList=new ArrayList<>();
bookList.add(new Book("The King","Tom","1955"));
bookList.add(new Book("The King Tail","Jack","1956"));
bookList.add(new Book("The King Tail","Bean","1957"));
bookList.add(new Book("The King Help","Bean","1957"));
// 注意Key值重复时处理,这里是保存旧的值,之前加入的数据
// Function<? super T, ? extends K> keyMapper
// Function<? super T, ? extends U> valueMapper->Function.identity()
// BinaryOperator<U> mergeFunction
return bookList.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(),(oldValue,newValue)->oldValue));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Book{
private String name;
private String author;
private String releaseYear;
}
①、合并不覆盖旧值.
/**
* 转换Map,保存后者
* @return Map<String,Book>
*/
private static Map<String,Book> convertNewValueMap(){
List<Book> bookList=new ArrayList<>();
bookList.add(new Book("The King","Tom","1955"));
bookList.add(new Book("The King Tail","Jack","1956"));
bookList.add(new Book("The King Tail","Bean","1957"));
bookList.add(new Book("The King Help","Bean","1957"));
// 注意Key值重复时处理,这里是保存新的值,也就是后面加入的数据
// Function<? super T, ? extends K> keyMapper
// Function<? super T, ? extends U> valueMapper->Function.identity()
// BinaryOperator<U> mergeFunction
return bookList.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(),(oldValue,newValue)->newValue));
}
②、合并覆盖旧值.
List对象属性分组过滤
class UserInfo{
private Long id;
private String name;
private Integer age;
public UserInfo(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
return Objects.equals(id, userInfo.id) &&
Objects.equals(name, userInfo.name) &&
Objects.equals(age, userInfo.age);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
}
List对象去重,记得重写hashcode和equals方法.
List<UserInfo> infoList = userInfoList.stream().distinct().collect(Collectors.toList());
System.out.println(infoList);
List<UserInfo> userInfoList=new ArrayList<>();
userInfoList.add(new UserInfo(1L, "Tom", 23));
userInfoList.add(new UserInfo(2L, "Jack", 24));
userInfoList.add(new UserInfo(3L, "Luck", 25));
userInfoList.add(new UserInfo(4L, "Luck", 26));
// Stream属性分组过滤
Map<String, List<UserInfo>> collect = userInfoList.stream().collect(Collectors.groupingBy(UserInfo::getName));
System.out.println(collect);
传统的Map属性分组
Map<String, List<UserInfo>> result = new HashMap<>();
// 转换
for(UserInfo userInfo:userInfoList){
String name = userInfo.getName();
List<UserInfo> list = result.get(name);
if(CollectionUtils.isEmpty(list)){
list = new ArrayList<>();
result.put(name, list);
}
// 存在直接添加list中即可
list.add(userInfo);
}
List<Map<String,Object>>过滤指定的值,返回过滤后的集合。Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)
public static void testObjectMap(){
List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> mapOne = new HashMap<>();
mapOne.put("key1","value1");
mapOne.put("key2","value2");
mapOne.put("key3","value3");
mapOne.put("key4","value4");
Map<String,Object> mapTwo = new HashMap<>();
mapTwo.put("key1","value1");
mapTwo.put("key2","value2");
mapTwo.put("key3","value3");
mapTwo.put("key4","value4");
Map<String,Object> mapThree = new HashMap<>();
mapThree.put("key1","value1");
mapThree.put("key2","value2");
mapThree.put("key3","value3");
mapThree.put("key4","value4");
list.add(mapOne);
list.add(mapTwo);
list.add(mapThree);
// List的条件过滤
List<Map<String, Object>> collect = list.stream().map
(m -> m.entrySet().stream().filter(map -> !map.getKey().equals("key4")).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))).collect(Collectors.toList());
System.out.println(collect);
// Map的条件过滤
Map<String, Object> result = mapThree.entrySet().stream().filter(map -> !map.getKey().equals("key4")).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(result);
}
}
Stream流下的map和flapMap使用示例
package com.boot.skywalk.stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FlatMap {
public static void main(String[] args) {
List<TempOut> result = new ArrayList<>();
TempOut tempOut1 = new TempOut("01", Arrays.asList(new TempEntity("001", "temp1"), new TempEntity("002", "temp1"), new TempEntity("003", "temp1")));
TempOut tempOut2 = new TempOut("02", Arrays.asList(new TempEntity("001", "temp2"), new TempEntity("002", "temp2"), new TempEntity("003", "temp2")));
TempOut tempOut3 = new TempOut("03", Arrays.asList(new TempEntity("001", "temp3"), new TempEntity("002", "temp3"), new TempEntity("003", "temp3")));
result.add(tempOut1);
result.add(tempOut2);
result.add(tempOut3);
// map转换
List<List<TempEntity>> mapResult = result.stream().map(item -> item.getTempEntityList()).collect(Collectors.toList());
// flatMap转换
List<TempEntity> flatMapResult = result.stream().flatMap(item -> item.getTempEntityList().stream()).collect(Collectors.toList());
System.out.println(mapResult);
System.out.println(flatMapResult);
}
}
class TempOut {
private String id;
private List<TempEntity> tempEntityList;
public TempOut(String id, List<TempEntity> tempEntityList) {
this.id = id;
this.tempEntityList = tempEntityList;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<TempEntity> getTempEntityList() {
return tempEntityList;
}
public void setTempEntityList(List<TempEntity> tempEntityList) {
this.tempEntityList = tempEntityList;
}
@Override
public String toString() {
return "TempOut{" +
"id='" + id + '\'' +
", tempEntityList=" + tempEntityList +
'}';
}
}
class TempEntity {
private String id;
private String name;
public TempEntity(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TempEntity{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}