Java常见类型操作方式
Java中遍历Map的几种常见方式
List
计算List求和或List对象中某个字段的总和
一. 使用循环遍历List对象,累加求和
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("List总和:" + sum);
如果要计算List中某个字段的总和,假设有一个包含Person对象的List,每个Person对象有一个age字段:
List<Person> persons = Arrays.asList(
new Person("John", 25),
new Person("Jane", 30),
new Person("Mike", 35)
);
int sum = 0;
for (Person person : persons) {
sum += person.getAge();
}
System.out.println("年龄总和:" + sum);
二. Java 8的Stream API,list stream:计算对象List中某个字段的总和
1. 计算一个number类型的List对象总和
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("List总和:" + sum);
或者
Integer[] integerArray = {1, 3, 5, 10, 18};
List<Integer> list = new ArrayList<>(Arrays.asList(integerArray));
IntSummaryStatistics summaryStatistics = list.stream().mapToInt((s) -> s).summaryStatistics();
System.out.println("总和:" + summaryStatistics.getSum());
System.out.println("平均数:" + summaryStatistics.getAverage());
System.out.println("总个数:" + summaryStatistics.getCount());
System.out.println("最大值:" + summaryStatistics.getMax());
System.out.println("最小值:" + summaryStatistics.getMin());
2. 计算一个List对象中某个字段总和
List<Person> persons = Arrays.asList(
new Person("John", 25),
new Person("Jane", 30),
new Person("Mike", 35)
);
int sum = persons.stream().mapToInt(Person::getAge).sum();
System.out.println("年龄总和:" + sum);
或者
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(10);
userList.add(user1);
User user2 = new User();
user2.setAge(20);
userList.add(user2);
User user3 = new User();
user3.setAge(25);
userList.add(user3);
int ageSum = userList.stream().collect(Collectors.summingInt(User::getAge));
System.out.println("年龄总和 :" + ageSum);
3. Java Stream 计算总和 Stream聚合函数对BigDecimal求和
BigDecimal sum = selectList.stream().map(SxLoss::getLossAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
注意:有可能会报错,因为对象中某个值为空,因此需要增加判断
BigDecimal sum = selectList.stream().map(SxLoss::getLossAmount).filter(lossAmount -> lossAmount != null).reduce(BigDecimal.ZERO, BigDecimal::add);
注:以上几种方法都可以计算List的总和或List对象中某个字段的总和。选择使用哪种方法取决于具体的需求和使用的Java版本。
Map
Java中遍历Map的几种常见方式
在Java中,可以使用不同的方式来遍历Map,以下是常见的几种方式:
1. 使用迭代器遍历Map
使用Map.Entry对象的迭代器来遍历Map中的键值对,示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
2. 使用foreach循环遍历Map
使用foreach循环遍历Map中的键值对,示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
3. 使用Lambda表达式和Stream API遍历Map
使用Lambda表达式和Stream API遍历Map中的键值对,示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.entrySet().stream().forEach(entry -> {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
});
4. 使用Java 8中的forEach()方法遍历Map
使用Java 8中的forEach()方法遍历Map中的键值对,示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.forEach((key, value) -> System.out.println(key + ": " + value));
需要注意的是,以上方式都是遍历Map中的键值对,如果只需要遍历Map中的键或值,也可以使用keySet()或values()方法来获取相应的集合,然后使用迭代器或Stream API遍历它们。
计算所有Map值的总和
可以使用 values() 方法。现在任务简化为汇总集合中的所有值。这可以在 Java 中以多种方式完成:
1. 使用 Java 8
在 Java 8 或更高版本中,可以使用 Streams 轻松完成求和运算,而无需任何循环。
import java.util.HashMap;
import java.util.Map;
public class Main{
public static void main(String[] args){
Map<String, Integer> persons = new HashMap<>();
persons.put("John", 25);
persons.put("Neil", 15);
persons.put("Rosy", 18);
int sum = persons.values().stream().mapToInt(Integer::intValue).sum();
System.out.println(sum); // 58
}
}
还可以使用 reduce() 方法。
import java.util.HashMap;
import java.util.Map;
public class Main
{
public static void main(String[] args)
{
Map<String, Integer> persons = new HashMap<>();
persons.put("John", 25);
persons.put("Neil", 15);
persons.put("Rosy", 18);
int sum = persons.values().stream().reduce(0, Integer::sum);
System.out.println(sum); // 58
}
}
2. 使用for循环
在 Java 8 之前,我们可以使用简单的 for 循环替换 Stream API 链:
import java.util.HashMap;
import java.util.Map;
public class Main{
public static void main(String[] args){
Map<String, Integer> persons = new HashMap<>();
persons.put("John", 25);
persons.put("Neil", 15);
persons.put("Rosy", 18);
int sum = 0;
for (int value: persons.values()) {
sum += value;
}
System.out.println(sum); // 58
}
}
这就是计算 a 中所有值的总和 Map<?, Integer> 在Java。
Json转换的常见操作方式
利用阿里巴巴封装的FastJSON来转换json字符串
package com.zkn.newlearn.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
/**
* JSON字符串自动转换
* Created by zkn on 2016/8/22.
*/
public class JsonToMapTest01 {
public static void main(String[] args){
String str = "{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}";
//第一种方式
Map maps = (Map)JSON.parse(str);
System.out.println("这个是用JSON类来解析JSON字符串!!!");
for (Object map : maps.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" " + ((Map.Entry)map).getValue());
}
//第二种方式
Map mapTypes = JSON.parseObject(str);
System.out.println("这个是用JSON类的parseObject来解析JSON字符串!!!");
for (Object obj : mapTypes.keySet()){
System.out.println("key为:"+obj+"值为:"+mapTypes.get(obj));
}
//第三种方式
Map mapType = JSON.parseObject(str,Map.class);
System.out.println("这个是用JSON类,指定解析类型,来解析JSON字符串!!!");
for (Object obj : mapType.keySet()){
System.out.println("key为:"+obj+"值为:"+mapType.get(obj));
}
//第四种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map json = (Map) JSONObject.parse(str);
System.out.println("这个是用JSONObject类的parse方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第五种方式
/**
* JSONObject是Map接口的一个实现类
*/
JSONObject jsonObject = JSONObject.parseObject(str);
System.out.println("这个是用JSONObject的parseObject方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第六种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map mapObj = JSONObject.parseObject(str,Map.class);
System.out.println("这个是用JSONObject的parseObject方法并执行返回类型来解析JSON字符串!!!");
for (Object map: json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
System.out.println(json);
}
}
更新:2026-05-01

评论区