Map集合 适合做购物车
键值对集合
key value
maps常用的方法
public class MapDemo {
public static void main(String[] args) {
//map 添加元素用put
Map<String, Integer> maps = new HashMap<>();
maps.put("iphonex", 11);
maps.put("iphonex", 33);
maps.put("生活用品", 10);
maps.put("手表", 10);
maps.put("华为", 100);
System.out.println(maps);
// //清空集合
// maps.clear();
// System.out.println(maps);
// //判断是否为空
// System.out.println(maps.isEmpty());
//根据键获取对应值
Integer value = maps.get("手表");
System.out.println(value);
System.out.println(maps.get("手表"));//一行输出最优
//删除
maps.remove("iphonex");//删除键会返回值 可以取也可以不取
System.out.println(maps);
//判断是否包含某个键
System.out.println(maps.containsKey("手表"));
System.out.println(maps.containsKey("10"));
//判断是否包含某个数值
System.out.println(maps.containsValue(10));
System.out.println(maps.containsValue("10"));
//获取全部键的集合 键是无序的 返回的是个set 集合
//键的类型是字符串 用一个字符串的集合接收
Set<String> keys = maps.keySet();
for (String key : keys) {
System.out.println(key);
}
//获取全部值的内容
//map集合的值不做要求 可以重复 所以要用collection接 set集合不能重复
Collection<Integer> values = maps.values();
for (Integer num : values) {
System.out.println(num);
}
//集合的大小
System.out.println(maps.size());
//合并其他map集合
Map<String, Integer> maps2 = new HashMap<>();
maps2.put("小米", 1);
maps2.put("锤子", 10);
maps2.put("手表", 10000);
System.out.println(maps2);
//把maps2集合的全部元素倒入到maps里面
//相同键值被合并覆盖
maps.putAll(maps2);
System.out.println(maps);
}
}
maps遍历的方式
public class MapDemo2 {
public static void main(String[] args) {
Map<String, Integer> maps = new HashMap<>();
maps.put("iphonex", 11);
maps.put("iphonex", 33);
maps.put("生活用品", 10);
maps.put("手表", 10);
maps.put("华为", 100);
System.out.println(maps);
//键找值的方法遍历
//获取当前map集合的全部键集合
//先定义一个set集合接收键 然后再遍历集合 用数值接收值
Set<String> keys = maps.keySet();
System.out.println(keys);
//遍历一个键 取一个数值
for (String key : keys) {
Integer value = maps.get(key);
System.out.println(key + value);
}
//键值对的方式 代码复杂但是面向对象
// 键值对 整体当成一个循环 把map集合通过
// <Map.Entry<K, V> >entrySet() 转换成set集合
// entries=[(手表=10), (生活用品=10), (华为=100), (iphonex=33)] map.entry map的实体类型
Set<Map.Entry<String, Integer>> entries = maps.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
//取键值是同时进行的
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + value);
}
//jdk 1.8之后 lamada形式 非常的简单便捷 使用率80%
//长期支持办jdk11 最新的支持版本
maps.forEach((k, v) -> {
System.out.println(k + "=>" + v);
});
// maps.forEach((k, v) -> {
// System.out.println(k + "==>" + v);
// });
}
}
map存储自定义集合、linked Hashmap
浮点型自己比较大小的api
Double.compare(this.price, ((Pig) o).price);
用map统计字符串中字符出现的次数
public class TestDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入字符串");
String str = scanner.nextLine();
//容器先定义好 字符类型 LINKED可以保存顺序
Map<Character, Integer> maps = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
//取出当前索引的字符 取出的是字符形式
char ch = str.charAt(i);
//如果集合包含这个键 那么就出现过
if (maps.containsKey(ch)) {
//他的数值加1 对应的值得到加1maps.get(ch) 再重新存进去
maps.put(ch, maps.get(ch) + 1);
} else {
maps.put(ch, 1);
}
}
//输出结果
System.out.println(maps);
}
}
难度升级一点点 统计一句话里面单词出现次数 先用split 把字符串分割成为单词 在统计
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Map<String, Integer> maps = new HashMap<>();
String[] strs = str.split(" ");
for (String s : strs) {
if (maps.containsKey(s)) {
maps.put(s, maps.get(s) + 1);
} else {
maps.put(s, 1);
}
}
System.out.println(maps);
}
map 实现用字符串 列表的形式添加内容 究极进化
public class TestDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("张三丰,北京");
list.add("李四丰,上海");
list.add("王二小,北京");
list.add("小明,河北");
list.add("小毛,北京");
list.add("王五,北京");
//把地址作为 string 人名作为list 一个地方可以有好几个人
//北京 【 张三丰,小毛,王五】
Map<String, List<String>> maps = new HashMap<>();
for (String s : list) {
//用逗号分割开
//默认知道 分为两个部分 用0 1 表示
String[] strings = s.split(",");
//如果已经存在某个地址了 那么就在该地址对应的人名列表上 加上人名
boolean flag = maps.containsKey(strings[1]);
//不包含 新建一个列表
if (!flag) {
maps.put(strings[1], new ArrayList<>());
//直接给对应的key 的value 赋值 即list增加元素
maps.get(strings[1]).add(strings[0]);
} else {
//如果存在了人名可以直接给对应的键 对应的列表加值
maps.get(strings[1]).add(strings[0]);
}
}
for (String s : maps.keySet()) {
// 键key 还有对应的值 value
System.out.println(s + maps.get(s) + maps.get(s).size());
}
}
}
根据所给的数值 找到对应的键 列表形式返回
public class TestDemo {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("aaa", "111");
map.put("bbb", "111");
map.put("ccc", "111");
map.put("ddd", "113");
// System.out.println(map);
System.out.println(getKeyByValue(map, "111"));
}
public static List<String> getKeyByValue(Map<String, String> map, String str) {
ArrayList<String> strings = new ArrayList<>();
//遍历map
Set<Map.Entry<String, String>> enries = map.entrySet();
for (Map.Entry<String, String> enry : enries) {
//key value 可以同时取值
String value = enry.getValue();
if (str.equals(value)) {
String key = enry.getKey();
strings.add(key);
}
}
// System.out.println(strings);
return strings;
}
}
重点 MAP的遍历
删除修改map里面的内容
//删除编号为1 的内容
System.out.println(map);
map.remove(1);
//更改编号为2的内容
map.put(2, "周林");
System.out.println(map);
list 16个国家分组 random不会用啊
public class TestDemo {
public static void main(String[] args) {
String[] str = {"科特迪瓦", "阿根廷", "澳大利亚", "塞尔维亚", "荷兰", "尼日利亚", "日本", "美国", "中国", "新西兰", "巴西", "比利时", "韩国", "喀麦隆",
"洪都拉斯", "意大利"};
List<String> listOne = new ArrayList<>();
for (int i = 0; i < str.length; i++) {
listOne.add(str[i]);
}
System.out.println(listOne);
//创建一个随机数生成器
Random ran = new Random();
//创建一个国家变量 输出和删除
String country;
//分成四组 两层循环 一次四个数组
for (int i = 1; i <= 4; i++) {
System.out.println(i + "组");
for (int j = 0; j < 4; j++) {
//ran.nextInt(listOne.size()) 链表的长度 随机数生成
//根据随机数的值 对应取列表的数值
country = listOne.get(ran.nextInt(listOne.size()));
System.out.println(" " + country);
//取出来显示之后把它从集合中删除 这样下次取不会再取到它
//按照值来
listOne.remove(country);
}
System.out.println("\n");
}
}
}
TreeSet排序
class Employee implements Comparable<Employee> {
@Override
public int compareTo(Employee o) {
//菜鸟代码
/**
//若果传进来的小于当前的
if (this.age > o.age) {
return 1;
} else if (this.age < o.age) {
return -1;
}
return 0;
*/
//升序
// return this.age - o.age;
//降序
return o.age - this.age;
}
重写比较器
public class TestDemo {
public static void main(String[] args) {
Set<Employee> employees = new TreeSet<>(new Comparator<Employee>() {
//比较年月日 同类型
@Override
public int compare(Employee o1, Employee o2) {
//要判断是不是同一个类型
if (o1 instanceof Employee && o2 instanceof Employee) {
Employee e1 = (Employee) o1;
Employee e2 = (Employee) o2;
MyDate b1 = e1.getBirthday();
MyDate b2 = e2.getBirthday();
//在Mydate里面调用
return b1.compareTo(b2);
}
throw new RuntimeException("传入数据有误");
}
});
Employee e1 = new Employee("JOE", 24, new MyDate(1997, 11, 7));
Employee e2 = new Employee("JACK", 22, new MyDate(1999, 1, 17));
Employee e3 = new Employee("ROSE", 20, new MyDate(2001, 8, 22));
employees.add(e1);
employees.add(e2);
employees.add(e3);
System.out.println(employees);
}
}
class Employee implements Comparable<Employee> {
private String name;
private int age;
private MyDate birthday;
public Employee(String name, int age, MyDate birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public Employee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
@Override
public int compareTo(Employee o) {
if (o instanceof Employee) {
Employee e = (Employee) o;
return this.name.compareTo(e.name);
}
throw new RuntimeException("传入的数据类型不一致");
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
}
class MyDate implements Comparable {
private int year;
private int month;
private int day;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public MyDate() {
}
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public int compareTo(Object o) {
if (o instanceof MyDate) {
MyDate myDate = (MyDate) o;
//比较年 比较大小只要不为0 就返回一个数值
int minusYear = this.getYear() - myDate.getYear();
if (minusYear != 0) {
return minusYear;
}
//直接比较月 不需要else
int minusMonth = this.getMonth() - myDate.getMonth();
if (minusMonth != 0) {
return minusMonth;
}
//比较日
int minusDay = this.getDay() - myDate.getDay();
if (minusDay != 0) {
return minusDay;
}
}
throw new RuntimeException("不存在");
}
@Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}
map 根据值的大小排序 写的非常的专业标准的一个版本
public class TestDemo {
public static void main(String[] args) {
Map<String, Integer> maps = new HashMap<>();
maps.put("a", 22);
maps.put("b", 11);
maps.put("c", 2);
maps.put("d", 99);
System.out.println(maps.toString());
//降序
maps = MapValueSortUtils.sortDescend(maps);
System.out.println(maps.toString());
//升序
maps = MapValueSortUtils.sortAscend(maps);
//排序后
System.out.println(maps.toString());
}
}
//写一个map功能排序
class MapValueSortUtils {
//map的value降序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
int compare = (o1.getValue()).compareTo(o2.getValue());
return -compare;
}
});
Map<K, V> returnMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
// Map的value值升序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortAscend(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
int compare = (o1.getValue()).compareTo(o2.getValue());
return compare;
}
});
Map<K, V> returnMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
}
//将Map转为List ,进行排序
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list,((o1, o2) -> o2.getValue().compareTo(o1.getValue())));