1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
-- 确定一年内的天数
select add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y') from dual

-- 查询emp员工表下部门工资前二名的员工信息'
select deptno ,ename,sal from emp e1
where
(select count(1) from emp e2
where e2.deptno=e1.deptno and e2.ename != e1.ename and e2.sal >e1.sal)<2
order by deptno , sal desc

-----
select * from
(select deptno,ename,sal,row_number() over (partition by deptno
order by sal desc) rn
from emp)
where rn <3
--- 查询某用户下所有表
select table_name from all_tables where owner = 'SCOTT'

--- 分页查询1
select * from (select rownum no,e.* from
(select * from emp order by sal desc) e where rownum <5)where no>3
-- 分页查询2
select *
from
(select rownum no,e.* from (select * from emp order by sal desc) e)
where
no>3 and no<10

-- 随机返回5条数据
select * from (select ename,job from emp order by dbms_random.value()) where rownum<=5
-- 处理空值排序
select * from emp order by comm desc nulls last --(first)
-- 查询跳过表的偶数行
select ename from (select row_number() over (order by ename) rn ,ename from emp) where mod(rn,2) =1
-- 查询员工信息与其中工资最高员工最低员工
select ename,sal,max(sal) over(),min(sal) over() from emp
--连续求和
select ename,sal,sum(sal) over(),sum(sal) over(order by ename) from emp;
-- 分部门连续求和
select deptno ,sal ,sum(sal) over(partition by deptno order by ename) as s from emp;

--得到上一行下一行数据
select ename,sal,lead(sal) over (order by sal) aaa,lag(sal) over (order by sal) bbb from emp;
分享到
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBHelper {

private final static String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private final static String URL="jdbc:sqlserver://127.0.0.1:1433;database=taobaoDB";
private final static String Name="sa";
private final static String Pwd="123456";

public static Connection getConn(){

Connection conn = null;
try {
Class.forName(DRIVER); //加载驱动
conn = DriverManager.getConnection(URL, Name, Pwd);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

/* //测试连接
public static void main(String[] args) {
System.out.println(getConn());
}*/

public void close(Connection conn,PreparedStatement ps,ResultSet rs){
if(rs !=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps !=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn !=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}
分享到

java统计字符串中字符出现的次数

1. 使用java原生方式for循环

1
2
3
4
5
6
7
8
9
10
String someString = "elephant";
char someChar = 'e';
int count = 0;

for (int i = 0; i < someString.length(); i++) {
if (someString.charAt(i) == someChar) {
count++;
}
}
assertEquals(2, count);

2. 使用java原生递归调用

1
2
3
4
5
6
7
8
9
10
private static int countOccurences(
String someString, char searchedChar, int index) {
if (index >= someString.length()) {
return 0;
}

int count = someString.charAt(index) == searchedChar ? 1 : 0;
return count + countOccurences(
someString, searchedChar, index + 1);
}

3. 使用正则表达式

1
2
3
4
5
6
7
8
Pattern pattern = Pattern.compile("[^e]*e");
Matcher matcher = pattern.matcher("elephant");
int count = 0;
while (matcher.find()) {
count++;
}

assertEquals(2, count);

4.使用java8

1
2
3
4
5
6
String someString = "elephant";
long count = someString.chars().filter(ch -> ch == 'e').count();
assertEquals(2, count);

long count2 = someString.codePoints().filter(ch -> ch == 'e').count();
assertEquals(2, count2);

使用外部jar包

5. 使用lang包

1
2
int count = StringUtils.countMatches("elephant", "e");
assertEquals(2, count);

6. 使用guava

1
2
int count = CharMatcher.is('e').countIn("elephant");
assertEquals(2, count);

7.使用spring utils

1
2
int count = StringUtils.countOccurrencesOf("elephant", "e");
assertEquals(2, count);

总结: 原生方式简单粗暴,也可以使用其他工具类,但使用java8感觉最优雅.

分享到

java的字符串转枚举类型

假定一个美酒类型

1
PizzaStatusEnum readyStatus = PizzaStatusEnum.READY;

使用 valueOf(“”)方法

1
2
3
4
5
6
7
8
@Test
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {

String pizzaEnumValue = "READY";
PizzaStatusEnum pizzaStatusEnum
= PizzaStatusEnum.valueOf(pizzaEnumValue);
assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
}

注意: 如果参数不对,会抛出非法参数异常

1
2
3
4
5
@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "invalid";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
分享到

java截取字符串的最后一个字符方法

1. 原生java方式 先判断是否为空

1
2
3
4
5
public static String removeLastChar(String s) {
return (s == null || s.length() == 0)
? null
: (s.substring(0, s.length() - 1));
}

2. 使用java8

1
2
3
4
5
6
public static String removeLastCharOptional(String s) {
    return Optional.ofNullable(s)
      .filter(str -> str.length() != 0)
      .map(str -> str.substring(0, str.length() - 1))
      .orElse(s);
}

3. 使用 apache common lang StringUtils.substring()

1
2
String TEST_STRING = "ACBDEF";
StringUtils.substring(TEST_STRING,0,TEST_STRING.length()-1);

4. 使用 StringUtils.chop()方法 因对边缘场景的情况(empty or null)时

1
StringUtils.chop(TEST_STRING)

5. 使用replaceAll() 的正则表达式方式

1
2
3
4
5
6
7
8
9
public static String removeLastCharRegex(String s) {
return (s == null) ? null : s.replaceAll(".$", "");
}
// java8
public static String removeLastCharRegexOptional(String s) {
return Optional.ofNullable(s)
.map(str -> str.replaceAll(".$", ""))
.orElse(s);
}

总结: 以上主要使用substring方法截取字符串,复杂的话建议使用正则表达式方式处理。

分享到

java生成随机字符串的五种方式

1. 使用原生java生成无边界字符串

1
2
3
4
5
6
7
8
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));

System.out.println(generatedString);
}

2.使用原生java生成右边界字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {

int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();
StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
int randomLimitedInt = leftLimit + (int)
(random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
String generatedString = buffer.toString();

System.out.println(generatedString);
}

3.使用 apache common lang 生成有边界字符串(只用字母)

1
2
3
4
5
6
7
8
9
10
@Test
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
  
    int length = 10;
    boolean useLetters = true;
    boolean useNumbers = false;
    String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
 
    System.out.println(generatedString);
}

4. 使用 apache common lang 生成有边界字母

1
2
3
4
5
6
@Test
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
String generatedString = RandomStringUtils.randomAlphabetic(10);

System.out.println(generatedString);
}

5. 使用 apache common lang 生成有边界字母和数字

1
2
3
4
5
@Test
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
String generatedString = RandomStringUtils.randomAlphanumeric(10);
System.out.println(generatedString);
}

总结: 使用lang包的生成方式简单,自己原生方式也可以实现.

分享到

java字符类型转字符串类型六种方式

1. 使用String.valueOf()方法

1
2
3
4
5
6
7
8
@Test
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
char givenChar = 'x';

String result = String.valueOf(givenChar);

assertThat(result).isEqualTo("x");
}

2. 使用 Character.toString() 方法

1
2
3
4
5
6
7
8
@Test
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() {
char givenChar = 'x';

String result = Character.toString(givenChar);

assertThat(result).isEqualTo("x");
}

3. 使用Character的构造方法

1
2
3
4
5
6
7
8
@Test
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString() {
char givenChar = 'x';

String result = new Character(givenChar).toString();

assertThat(result).isEqualTo("x");
}

4. 通过String的隐式转换

1
2
3
4
5
6
7
8
@Test
public void givenChar_whenConcatenated_shouldConvertToString() {
char givenChar = 'x';

String result = givenChar + "";

assertThat(result).isEqualTo("x");
}

5.

1
2
3
4
5
6
7
8
@Test
public void givenChar_whenFormated_shouldConvertToString() {
char givenChar = 'x';

String result = String.format("%c", givenChar);

assertThat(result).isEqualTo("x");
}

总结: 常用Stirng的隐式转换方式.

分享到

java回文数字判断方式

1. 使用原生java方式

1
2
3
4
5
6
7
8
9
10
11
12
13
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) { //两边指针同时变动,比较.
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}

2. 使用字符串reverse比较

1
2
3
4
5
6
7
8
9
public boolean isPalindromeReverseTheString(String text) {
    StringBuilder reverse = new StringBuilder();
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    char[] plain = clean.toCharArray();
    for (int i = plain.length - 1; i >= 0; i--) {
        reverse.append(plain[i]);
    }
    return (reverse.toString()).equals(clean);
}

3. 使用stringbuffer stringbuilder直接翻转字符串比较

1
2
3
4
5
6
7
8
9
10
11
12
13
public boolean isPalindromeUsingStringBuilder(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
StringBuilder plain = new StringBuilder(clean);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}

public boolean isPalindromeUsingStringBuffer(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
StringBuffer plain = new StringBuffer(clean);
StringBuffer reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}

4. 使用java8 intStream

1
2
3
4
5
public boolean isPalindromeUsingIntStream(String text) {
String temp = text.replaceAll("\\s+", "").toLowerCase();
return IntStream.range(0, temp.length() / 2)
.noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}

5. 使用递归调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public boolean isPalindromeRecursive(String text){
String clean = text.replaceAll("\\s+", "").toLowerCase();
return recursivePalindrome(clean,0,clean.length()-1);
}

private boolean recursivePalindrome(String text, int forward, int backward) {
if (forward == backward) {
return true;
}
if ((text.charAt(forward)) != (text.charAt(backward))) {
return false;
}
if (forward < backward + 1) {
return recursivePalindrome(text, forward + 1, backward - 1);
}

return true;
}

总结: 回文数验证分两种 一种是移动下标比较 另一种是 翻转 比较,翻转比较性能没有下标比较好,
所以建议使用java8 InStreannomatch方法

分享到

java分割字符串的三种方式

使用java原生String.split()方法

1
2
3
4
5
String[] splitted = "peter,james,thomas".split(",");  // 逗号分割
String[] splitted = "car jeep scooter".split(" "); // 空格分割
String[] splitted = "192.168.1.178".split("\\.") // 点分割

String[] splitted = "b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*")); //则这表达式多个分割符

使用工具类Common包下的StringUtils.split()方法

1
String[] splitted = StringUtils.split("car jeep scooter"); //默认空白分割

使用guava工具包的Splitter

1
2
3
4
List<String> resultList = Splitter.on(',')
.trimResults()
.omitEmptyStrings()
.splitToList("car,jeep,, scooter");

总结: String成员方法分割字符串处理简单分割比较容易,但是复杂一点使用工具类还是比较方法. 预先善其事必先利其器,多学习一些工具类的使用,提高开发效率也还不错.

分享到

java使用apache common工具类

查询字符串中出现任意字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String string = "baeldung.com";
boolean contained1 = StringUtils.containsAny(string, 'a', 'b', 'c');
boolean contained2 = StringUtils.containsAny(string, 'x', 'y', 'z');
boolean contained3 = StringUtils.containsAny(string, "abc");
boolean contained4 = StringUtils.containsAny(string, "xyz");

assertTrue(contained1);
assertFalse(contained2);
assertTrue(contained3);
assertFalse(contained4);
// 忽略大小写
String string = "matosiki.com";
boolean contained = StringUtils.containsIgnoreCase(string, "MATOSIKI");

assertTrue(contained);

匹配出现次数方法

1
2
3
4
5
6
String string = "welcome to www.matosiki.com";
int charNum = StringUtils.countMatches(string, 'w');
int stringNum = StringUtils.countMatches(string, "com");

assertEquals(4, charNum);
assertEquals(2, stringNum);

匹配前缀和后缀的方法

1
2
3
4
5
6
String string = "matosiki.com";
String stringWithSuffix = StringUtils.appendIfMissing(string, ".com");
String stringWithPrefix = StringUtils.prependIfMissing(string, "www.");

assertEquals("matosiki.com", stringWithSuffix);
assertEquals("www.matosiki.com", stringWithPrefix);

改变大小写

1
2
3
4
5
6
7
8
9
10
11
12
13
String originalString = "matosiki.COM";
String swappedString = StringUtils.swapCase(originalString);

assertEquals("MATOSIKI.com", swappedString);

// 首字母大写
String capitalizedString = StringUtils.capitalize(originalString);

assertEquals("Matosiki.COM", capitalizedString);
//首字母不大写
String uncapitalizedString = StringUtils.uncapitalize(originalString);

assertEquals("matosiki.COM", uncapitalizedString);

翻转字符串

1
2
3
4
5
6
7
8
9
String originalString = "matosiki";
String reversedString = StringUtils.reverse(originalString);

assertEquals("ikisotam", reversedString);
// 分割式翻转
String originalString = "www.matosiki.com";
String reversedString = StringUtils.reverseDelimited(originalString, '.');

assertEquals("com.matosiki.www", reversedString);

使用rotate()方法旋转

1
2
3
4
String originalString = "matosiki";
String rotatedString = StringUtils.rotate(originalString, 4);

assertEquals("sikimatos", rotatedString);

比较不同

1
2
3
4
5
6
7
String tutorials = "Baeldung Tutorials";
String courses = "Baeldung Courses";
String diff1 = StringUtils.difference(tutorials, courses);
String diff2 = StringUtils.difference(courses, tutorials);

assertEquals("Courses", diff1);
assertEquals("Tutorials", diff2);

总结: 使用StringUtils对字符串进行一些常用操作

分享到