1、lambda表达式对两个List进行循环,根据符合条件,进行相关的赋值操作并返回这个对象集合
public static <T, U> List<T> setListByEqualObjProperty(List<T> sourceList, String srcEqualProp, String srcSetProp,
List<U> targetList, String tarEqualProp, String tarGetProp) {
List<T> resultList = Lists.newArrayList();
resultList = sourceList.stream()
.map(sur -> targetList.stream()
.filter(tar -> Objects.equals(getValueByPropName(sur, srcEqualProp), getValueByPropName(tar, tarEqualProp)))
.findFirst()
.map(tar -> {
setValueByPropName(sur, srcSetProp, getValueByPropName(tar, tarGetProp));
return sur;
}).orElse(sur))
.collect(Collectors.toList());
return resultList;
}
public static <T> T getValueByPropName(Object object, String propName) {
T value = null;
try {
Field field = object.getClass().getDeclaredField(propName);
field.setAccessible(true);
value = (T) field.get(object);
} catch (Exception e) {
return null;
}
return value;
}
public static <U> void setValueByPropName(Object object, String propName, U updateValue) {
try {
Field field = object.getClass().getDeclaredField(propName);
field.setAccessible(true);
field.set(object, updateValue);
} catch (Exception e) {
e.printStackTrace();
}
}
2、将Object对象里面的属性和值转化成Map对象
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
3、MD5加密
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class MD5Utils {
public static String getSign(Map<String, Object> paramMap, String appSecret) {
List<String> keyList = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
keyList.add(entry.getKey());
}
Collections.sort(keyList);
StringBuffer sb = new StringBuffer();
sb.append(appSecret);
for (int i = 0; i < keyList.size(); i++) {
String key = keyList.get(i);
sb.append(key);
sb.append(paramMap.get(key));
}
sb.append(appSecret);
String paramsStr = sb.toString();
String sign_md5 = MD5Utils.MD5(paramsStr);
return sign_md5;
}
public static String MD5(String s) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
try {
byte[] btInput = s.getBytes();
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
}
4、基于 httpclient 4.3.1版本的 http工具类
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class HttpClient {
private static final CloseableHttpClient httpClient;
private static final CloseableHttpClient httpsClient;
public static final String CHARSET = "UTF-8";
public static final String HTTP = "http";
public static final String HTTPS = "https";
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
X509TrustManager manager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
SSLConnectionSocketFactory scoketFactory = null;
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{manager}, null);
scoketFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
RequestConfig httpsConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", scoketFactory).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
httpsClient = HttpClientBuilder.create().setConnectionManager(connectionManager).setDefaultRequestConfig(httpsConfig).build();
}
public static String doGet(String url, Map<String, Object> params, String type) throws Exception {
if (type == "https") {
return doHttpGet(url, params, CHARSET, httpsClient);
}
return doHttpGet(url, params, CHARSET, httpClient);
}
public static String doPost(String url, Map<String, Object> params, String type) throws Exception {
if (type == "https") {
return doHttpPost(url, params, httpsClient);
}
return doHttpPost(url, params, httpClient);
}
public static String doHttpGet(String url, Map<String, Object> params, String charset, CloseableHttpClient httpClient) throws Exception {
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue()!=null){
String value = entry.getValue().toString();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}else {
pairs.add(new BasicNameValuePair(entry.getKey(), ""));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
throw e;
}
}
public static String doHttpPost(String url, Map<String, Object> params, CloseableHttpClient httpClient) throws Exception {
if (StringUtils.isBlank(url)) {
return null;
}
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue().toString();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
HttpPost httpPost = new HttpPost(url);
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
throw e;
}
}
public static CloseableHttpClient getHttpClient(){
return httpClient;
}
}
5、基于jfinal 的文件上传工具类
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import io.jboot.Jboot;
import io.jboot.web.controller.JbootControllerContext;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class FileUtils {
public List<Map<String,Object>> upload(List<UploadFile> files) throws Exception {
Integer userId = 1;
String path = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
List<Map<String,Object>> mapList = new ArrayList<>();
List<File> fileList = new ArrayList<>();
for (UploadFile file:files) {
File source = file.getFile();
String fileName = file.getFileName();
String extension = fileName.substring(fileName.lastIndexOf("."));
String prefix;
if(".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)){
prefix = "img";
fileName = generateWord() + extension;
}else{
prefix = "file";
fileName = userId + "-" + fileName;
}
Map<String,Object> map = new HashMap();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(source);
File targetDir = new File(Jboot.configValue("top.upload.savepath") + "/" + prefix + "/" + path);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
File target = new File(targetDir, fileName);
target.createNewFile();
fileList.add(target);
fos = new FileOutputStream(target);
byte[] bts = new byte[300];
while (fis.read(bts, 0, 300) != -1) {
fos.write(bts, 0, 300);
}
fos.close();
fis.close();
map.put("code", 0);
map.put("fileName", file.getFileName());
map.put("extension", extension);
map.put("file_addr", Jboot.configValue("top.upload.httppath") + "/" + prefix + "/" + path + "/" + fileName);
mapList.add(map);
} catch (FileNotFoundException e) {
fos.close();
fis.close();
map.put("code", 1);
map.put("message", "文件上传出现错误,请稍后再上传:" + file.getFileName());
mapList = new ArrayList<>();
mapList.add(map);
deleteFiles(fileList);
return mapList;
} catch (IOException e) {
map.put("code", 1);
map.put("message", "文件写入服务器出现错误,请稍后再上传:" + file.getFileName());
mapList = new ArrayList<>();
mapList.add(map);
fos.close();
fis.close();
deleteFiles(fileList);
return mapList;
} catch (Exception e){
fos.close();
fis.close();
map.put("code", 1);
map.put("message", "文件写入服务器出现错误,请稍后再上传:" + file.getFileName());
mapList = new ArrayList<>();
mapList.add(map);
deleteFiles(fileList);
return mapList;
}finally {
source.delete();
}
}
return mapList;
}
private String generateWord() {
String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
List<String> list = Arrays.asList(beforeShuffle);
Collections.shuffle(list);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
}
String afterShuffle = sb.toString();
String result = afterShuffle.substring(0, 9);
return result;
}
public void deleteFiles(List<File> fileList){
for (File file:fileList){
file.delete();
}
}
public static List<Map<String, Object>> getFilePath(){
Controller controller = JbootControllerContext.get();
List<UploadFile> file = controller.getFiles();
FileUtils fileUtils = new FileUtils();
List<Map<String, Object>> mapList = null;
try {
mapList = fileUtils.upload(file);
} catch (Exception e) {
e.printStackTrace();
}
return mapList;
}
}
6、java Stream()流的基本操作
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import java.util.stream.Collectors;
public class Testconttrol {
public static void main(String[] args) {
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<Integer> integers = Arrays.asList(1,2,2,13,4,15,6,17,8,19);
System.out.println(strings.stream().filter(string -> !string.isEmpty()).count());
System.out.println(strings.stream().filter(s -> s.length() == 3).count());
System.out.println(strings.stream().filter(s -> s.length() == 3).collect(Collectors.toList()));
System.out.println(strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList()));
String collect = result.stream().map(d -> d.get("serial_num").toString()).collect(Collectors.joining(","));
System.out.println(strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.joining(",")));
System.out.println(integers.stream().map(integer -> integer*integer).distinct().collect(Collectors.toList()));
System.out.println(integers.stream().map(integer -> integer*integer).collect(Collectors.toList()));
Double amount = trueResult.stream().map(a -> new BigDecimal(a.get("amount").toString())).reduce(BigDecimal::add).map(BigDecimal::doubleValue).orElse(0d);
IntSummaryStatistics intSummary = integers.stream().mapToInt((x)->x).summaryStatistics();
System.out.println(intSummary.getMax());
System.out.println(intSummary.getMin());
System.out.println(intSummary.getSum());
System.out.println(intSummary.getAverage());
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
}
public void test1(){
List<Map<String,Object>> list2 = new ArrayList<>();
Map<String,Object> map1 = new HashMap<>();
map1.put("region", "410185");
map1.put("positionText", "服务员");
map1.put("urgent", "1");
list2.add(map1);
Map<String,Object> map2 = new HashMap<>();
map2.put("region", "410100");
map2.put("positionText", "按摩师");
map2.put("urgent", "2");
list2.add(map2);
Map<String,Object> map3 = new HashMap<>();
map3.put("region", "410100");
map3.put("positionText", "服务员");
map3.put("urgent", "2");
list2.add(map3);
Map<String,Object> map4 = new HashMap<>();
map4.put("region", "410155");
map4.put("positionText", "会计");
map4.put("urgent", "1");
list2.add(map4);
List<Map<String, Object>> groupList = list2.stream().collect(Collectors.groupingBy(d -> d.get("region"))).entrySet()
.stream().map(d -> {
Map<String, Object> map = new HashMap<>();
map.put("recruitList", d.getValue());
map.put("region", d.getKey());
return map;
}).collect(Collectors.toList());
System.out.println(JSONObject.toJSON(groupList));
}
value.getValue().sort(Comparator.comparing(
(Function<AdsDomesticRicePurchasePrice, Date>) BaseAdsDomesticRicePurchasePrice::getTime
).reversed());
}
7、BigDecimal加减乘除计算
BigDecimal result1 = num1.add(num2);
BigDecimal result12 = num12.add(num22);
BigDecimal result2 = num1.subtract(num2);
BigDecimal result22 = num12.subtract(num22);
BigDecimal result3 = num1.multiply(num2);
BigDecimal result32 = num12.multiply(num22);
BigDecimal result4 = num3.abs();
BigDecimal result42 = num32.abs();
BigDecimal result5 = num2.divide(num1,20,BigDecimal.ROUND_HALF_UP);
BigDecimal result52 = num22.divide(num12,20,BigDecimal.ROUND_HALF_UP);
8、数字区间判断
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class CheckBetweenUtils {
public boolean isInTheInterval(String data_value,String interval) {
String formula = getFormulaByAllInterval(data_value,interval,"||");
ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
try {
return (Boolean) jse.eval(formula);
} catch (Exception t) {
return false;
}
}
private String getFormulaByAllInterval(String date_value, String interval, String connector) {
StringBuffer buff = new StringBuffer();
for(String limit:interval.split("U")){
buff.append("(").append(getFormulaByInterval(date_value, limit," && ")).append(")").append(connector);
}
String allLimitInvel = buff.toString();
int index = allLimitInvel.lastIndexOf(connector);
allLimitInvel = allLimitInvel.substring(0,index);
return allLimitInvel;
}
private String getFormulaByInterval(String date_value, String interval, String connector) {
StringBuffer buff = new StringBuffer();
for(String halfInterval:interval.split(",")){
buff.append(getFormulaByHalfInterval(halfInterval, date_value)).append(connector);
}
String limitInvel = buff.toString();
int index = limitInvel.lastIndexOf(connector);
limitInvel = limitInvel.substring(0,index);
return limitInvel;
}
private String getFormulaByHalfInterval(String halfInterval, String date_value) {
halfInterval = halfInterval.trim();
if(halfInterval.contains("∞")){
return "1 == 1";
}
StringBuffer formula = new StringBuffer();
String data = "";
String opera = "";
if(halfInterval.matches("^([<>≤≥\\[\\(]{1}(-?\\d+.?\\d*\\%?))$")){
opera = halfInterval.substring(0,1);
data = halfInterval.substring(1);
}else{
opera = halfInterval.substring(halfInterval.length()-1);
data = halfInterval.substring(0,halfInterval.length()-1);
}
double value = dealPercent(data);
formula.append(date_value).append(" ").append(opera).append(" ").append(value);
String a = formula.toString();
return a.replace("[", ">=").replace("(", ">").replace("]", "<=").replace(")", "<").replace("≤", "<=").replace("≥", ">=");
}
private double dealPercent(String str){
double d = 0.0;
if(str.contains("%")){
str = str.substring(0,str.length()-1);
d = Double.parseDouble(str)/100;
}else{
d = Double.parseDouble(str);
}
return d;
}
}
9、从互联网上下载图片并保存到本地服务器
import java.net.URL;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class ImageDownloader {
public static void main(String[] args) throws IOException {
String imageUrl = "https://example.com/image.jpg";
String fileName = "image.jpg";
URL url = new URL(imageUrl);
ReadableByteChannel channel = Channels.newChannel(url.openStream());
File file = new File("path/to/save/" + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);
channel.close();
outputStream.close();
System.out.println("图片已下载并保存到本地!");
}
}
10、java邮件发送
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication("你的电子邮件地址", "你的电子邮件密码");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("你的电子邮件地址"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("接收邮件的地址"));
message.setSubject("邮件主题");
message.setText("邮件内容");
Transport.send(message);
System.out.println("邮件已成功发送!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}