java常用方法

1、lambda表达式

/*** lambda表达式 */

// 循环
AtomicInteger total = new AtomicInteger(0);
productLogisticsDAOS.stream().forEach(dao -> {
int temp = dao.getAmount() * dao.getCount();
total.addAndGet(temp);
});

List<Integer> interceptProductIdList = interceptGoodsNumDAOS.stream().map(dao -> dao.getProductId()).distinct().collect(Collectors.toList());

List<DeliveryPackageDO> mainPackageDOList = packageDOS.stream().filter(dao -> dao.getTitle().equals(DriverPackageUtil.MAIN_PACKAGE_TEXT)).collect(Collectors.toList());


// 求和
Integer sum = detailDAOS.stream().mapToInt(DeliveryPackageGoodsDetailDAO::getNum).sum()
BigDecimal paymentAmount = purchaserAmountMap.values().stream().map(SupplierBillDetailVO::getAmount).reduce(BigDecimal::add).get();


/*** list转map */

// list转map-排序
LinkedHashMap<String, List<DeliveryOrderShopDAO>> addrMap = deliveryOrderShopDAOS.stream().collect(Collectors.groupingBy(DeliveryOrderShopDAO::getAddr_hash, LinkedHashMap::new, Collectors.toList()));

// list转map-多字段分组
Map<String, List<DeliveryGoodsDO>> deliveryGoodsMap = deliveryGoodsDOS.stream().collect(Collectors.groupingBy(item -> item.getVirtualgoodsId() + "_" + item.getTitle() + "_" + item.getSpec()));

// list转map-值为单个对象
Map<String, DeliveryDO> deliveryOrderMap = deliveryDOS.stream().collect(Collectors.toMap(DeliveryDO::getDeliveryOrder, (p) -> p));

// list转map-值为对象的字段
Map<Integer, Integer> goods2ProductParam = logisticsGoodsDAOS.stream().filter(dao -> goodsIdParamList.contains(dao.getGoodsId())).
collect(Collectors.toMap(LogisticsGoodsDAO::getGoodsId, LogisticsGoodsDAO::getProductId, (key1, key2) -> key2));



Optional.ofNullable(type).orElse(0).intValue();

public static final int cpuNum = Runtime.getRuntime().availableProcessors();

2、Map遍历

java中Map遍历的四种方式
https://www.cnblogs.com/damoblog/p/9124937.html

Map <String,String>map = new HashMap<String,String>();
map.put("熊大", "棕色");
map.put("熊二", "黄色");


for(Map.Entry<String, String> entry : map.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey+":"+mapValue);
}


//key
for(String key : map.keySet()){
System.out.println(key);
}
//value
for(String value : map.values()){
System.out.println(value);
}


Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}


for(String key : map.keySet()){
String value = map.get(key);
System.out.println(key+":"+value);
}

3、java排序

java排序

public static void main(String[] args) {
// 1、数组排序
int[] arr = {2, 3, 4, 5, 2, 1};
Arrays.sort(arr);
System.out.println(JSON.toJSON(arr));

// 2、列表排序
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(9);
list.add(3);
list.add(1);
Collections.sort(list);
System.out.println(JSON.toJSON(list));

Random random = new Random();
List<BuffProductNumDAO> numDAOList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
BuffProductNumDAO buffProductNumDAO = new BuffProductNumDAO();
buffProductNumDAO.setProductId(random.nextInt(10));
numDAOList.add(buffProductNumDAO);
}
System.out.format("Comparator before list=%s", JSON.toJSON(numDAOList));

// 3、Comparator排序
Collections.sort(numDAOList, new Comparator<BuffProductNumDAO>() {
@Override
public int compare(BuffProductNumDAO p1, BuffProductNumDAO p2) {
// 调用compare方法大于0,就把前一个数和后一个数交换,也就是把大的数放后面了,
// 即所谓的升序了。如果第二个参数与第一个参数调换顺序,也就是降序了。
int product = p2.getProductId() - p1.getProductId();
return product;
}
});
System.out.println();
System.out.format("Comparator after list=%s", JSON.toJSON(numDAOList));

Collections.sort(logisticsDAOList, Comparator.comparing(WarehouseLogisticsDAO::getSort).thenComparing(WarehouseLogisticsDAO::getDistance));


// 4、Comparable排序
List<Goods> goodsList = new ArrayList<>();
Collections.sort(goodsList);

}


// Goods
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods implements Comparable<Goods> { //实现Comparable接口,利用泛型限定比较的类型
private Integer productId; //商品编号
private String name; //商品名称
private double price; //商品价格

@Override
public int compareTo(Goods o) { //重写compareTo方法。
//取出商品价格
double price1 = this.getPrice();
double price2 = o.getPrice();
int n = new Double(price2 - price1).intValue(); //double类型的差值转为int
return n;
}
}
Java8排序stream.sorted() 
https://blog.csdn.net/qq_34996727/article/details/94472999

System.out.println("---Natural Sorting by Name---");
List<Student> slist = list.stream().sorted().collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));

System.out.println("---Natural Sorting by Name in reverse order---");
slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));

System.out.println("---Sorting using Comparator by Age---");
slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));

System.out.println("---Sorting using Comparator by Age with reverse order---");
slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));

4、flatmap,peek,newArrayList

JAVA8 中的flatmap

使用flatMap方法的效果是,各个数组并不是分别映射一个流,而是映射成流的内容,所有使用map(Array::stream)时生成的单个流被合并起来,即扁平化为一个流。
https://blog.csdn.net/liyantianmin/article/details/96178586
https://blog.csdn.net/zhuwukai/article/details/82888316
https://www.jianshu.com/p/ecb8e8f77a89

public static void main(String[] args) {
List<User> uList = Lists.newArrayList();
User u1 = new User();
u1.setAddr("a1;a2;a3;a4;a5");

User u2 = new User();
u2.setAddr("b1;b2;b3;b4;b5");

uList.add(u1);
uList.add(u2);

List<String> addrList = uList.stream().map(x -> x.getAddr()).flatMap(x-> Arrays.stream(x.split(";"))).collect(Collectors.toList());
//或者
List<String> ridStrList = uList.stream().map(x -> x.getAddr()).map(x -> x.split(";")).flatMap(Arrays::stream).collect(Collectors.toList());
System.out.println(addrList);
}

@Data
@NoArgsConstructor
public class User{
private String addr;
}
public static class User {
private String name;
private List<String> relativeUsers;
}

List<String> strings = users.stream()
.flatMap(user -> user.getRelativeUsers().stream())
.collect(Collectors.toList());
Java 8 Stream peek 与 map的区别
原文链接:https://blog.csdn.net/tckt75433/article/details/81510743
总结:peek接收一个没有返回值的λ表达式,可以做一些输出,外部处理等。map接收一个有返回值的λ表达式,之后Stream的泛型类型将转换为map参数λ表达式返回的类型。
几个快速添加list的方法
1. 使用Collections.addAll()方法,前提还是需要手动 new ArrayList
ArrayList<String> s = new ArrayList();
Collections.addAll(s,"1","2","3")

2. 使用Arrays.asList(...args) 直接返回一个List
List<String> s = Arrays.asList("1","2","3")

3. 如果引入了Guava的工具包,可以使用他的Lists.newArrayList(...args)方法
List<String> list = Lists.newArrayList("1","2","3")

4. 如果是Java9,可以使用自带的List类
List<String> s = List.of("1","2","3")
举报/反馈

无为徐生

92获赞 217粉丝
书法练习轨迹、编程笔记以及生活随笔。
关注
0
0
收藏
分享