java操作
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
###1.list轉(zhuǎn)map(將某一列作為key)
final ImmutableMap<Long, Position> indexPosition = Maps.uniqueIndex(positionList, new Function<Position, Long>() {@Overridepublic Long apply(Position input) {return input.getId();}});###2.list.indexof()查找的是指針:
List<Pet> pets = new ArrayList<Pet>(); pets.add(new Cat()); Cat cat=new Cat(); System.out.println(pets.indexOf(cat)); //output:-1###3.判斷列表為空
public static List<Integer> listEmpty(List<String> strs) {if (CollectionUtils.isEmpty(strs)){return Collections.emptyList();}}###4.string賦值并且判斷空
-
方法一:用guava,代碼量反而大
String key = null;String result = null;try {result = Preconditions.checkNotNull(key, "-");} catch (NullPointerException e) {result = e.getMessage();} -
方法二
String key = null;String result = (key == null) ? "-" : key; -
方法三:firstNonNull返回第一個非空對象,可以是自定義的類
String key = null;String result = Objects.firstNonNull(key, "-");
###5.帶查找和排序的類設(shè)計
public class DemoVo {private Integer id;private String name;private Integer curPage;//當(dāng)前頁碼private Integer pageSize;//分頁大小private Integer offset;//數(shù)據(jù)偏移量private String sortby;//排序條件private String orderby;//排序方式//計算分頁信息public Integer getOffset() {if (null == offset) {offset = (curPage - 1) * pageSize;}return offset;}//排序列取值范圍public static final ImmutableMap<String, String> SORTBY_MAP = ImmutableMap.of("id", "id", "name", "name");public static final ImmutableSet<String> ORDERBY_SET = ImmutableSet.of("asc", "desc");默認分頁大小public static final int DEFAULT_PAGESIZE = 30;/*** 默認當(dāng)前頁碼*/public static final int DEFAULT_CURPAGE = 1;/*** 默認排序*/public static final String DEFAULT_SORTBY = "name";/*** 默認排序方式*/public static final String DEFAULT_ORDERBY = "asc"; }-
排序設(shè)置方法
DemoVo demoVo = new DemoVo();if (!Strings.isNullOrEmpty(sortby) && demoVo.SORTBY_MAP.containsKey(sortby)) {demoVo.setSortby(sortby);}if (!Strings.isNullOrEmpty(orderby) && demoVo.ORDERBY_SET.contains(orderby)) {demoVo.setOrderby(orderby);}
###6.生成不可變map ####(1)kay,value都是string
public static final ImmutableMap<String, String> RANDOMS_VALUE=new ImmutableMap.Builder<String, String>().put("String","'abc'").put("Long", "123456").put("Integer", "123").put("Date", "20150401").put("Byte", "1").build();####(2)其他
public static final ImmutableMap<Integer, String> RANDOM=ImmutableMap.of(1, "a", 2, "b");###7.CharMatcher ####判斷是否包含某些字符
CharMatcher charMatcher=CharMatcher.anyOf("@*"); String key="asdf234@#$";if (charMatcher.matchesAnyOf(key)){System.out.println("it contains"); }####去掉首尾空格
String value=" private integer value"; String newStr=CharMatcher.WHITESPACE.trimAndCollapseFrom(value, ' ');####去掉尾部;號 String one="ahaha;"; CharMatcher charMatcher=CharMatcher.anyOf(";"); String two=charMatcher.trimTrailingFrom(one);
###8.取出List的某一列
public static void test1(){Person person1=new Person("a",18);Person person2=new Person("b", 2);List<Person> persons=Lists.newArrayList();persons.add(person1);persons.add(person2);List<String> names=Lists.transform(persons, new Function<Person, String>() {public String apply(Person arg0) {// TODO Auto-generated method stubreturn arg0.getName();}});System.out.println(Joiner.on(",").join(names)); }###9.httpclient post帶參數(shù)
//url及參數(shù)String url = URL;String resource = RESOURCE;String param=PARAMS;HttpClient client = new HttpClient();client.setConnectionTimeout(30000);client.setTimeout(30000);PostMethod post = new PostMethod(url);NameValuePair[] params ={ new NameValuePair("resource", resource),new NameValuePair("params", param), };post.setRequestBody(params);try {Integer statusCode = client.executeMethod(post);return post.getResponseBodyAsString();} catch (Exception e) {// TODO: handle exceptionlog.info("fengchao http error" + url, e);} finally {post.releaseConnection();}###10.數(shù)據(jù)庫表結(jié)構(gòu)相同的兩個表,java端賦值實體:
App app=new App(); AppHis appHis=new AppHis(); BeanUtils.copyProperties(appHis, app);###11.CaseFormat做字符轉(zhuǎn)換
CaseFormat-->caseFormat
String head = "CaseFormat";String name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, head);System.out.println(name);//caseFormat####格式,示例:
- LOWER_CAMEL lowerCamel
- LOWER_HYPHEN lower-hyphen
- LOWER__UNDERSCORE lower_underscore
- UPPER_CAMEL UpperCamel
- UPPER__UNDERSCORE UPPER__UNDERSCORE
###12.springmvc 傳入實例的列表
[@Data](https://my.oschina.net/difrik) public class Dormitory {private Long id;private List<Member> members;private String memberString;public List<Member> getMembers(){if (!members.isEmpty()){return members;}if (!Strings.isNullOrEmpty(memberString)){Gson gson=new Gson();members=gson.fromJson(memberString, new TypeToken<List<Member>>()){ }.getType());}return Collections.emptyList(); } }-
springmvc無法直接傳入列表,將數(shù)據(jù)傳給string,重寫列表的get方法,用gson自己解
-
gson可以用來在json和對象間轉(zhuǎn)換,json和泛型list轉(zhuǎn)換:
Dormitory dormitory = new Dormitory();dormitory.setId(1L);dormitory.setName("haha");// 類轉(zhuǎn)jsonGson gson = new Gson();String key = gson.toJson(dormitory);System.out.println(key);// json轉(zhuǎn)類Dormitory dorm = gson.fromJson(key, Dormitory.class);System.out.println(dorm.getName());
###13.map遍歷:用entry
Map<Long, String> maps = Maps.newHashMap();maps.put(1L, "a");maps.put(2L, "b");for (Entry<Long, String> entry : maps.entrySet()) {Long key = entry.getKey();String value = entry.getValue();System.out.println(key + ":" + value);}###14.編碼格式轉(zhuǎn)換
-
unicode是一種編碼規(guī)范,UTF-8屬于規(guī)范的一種實現(xiàn)。
-
無論哪種格式,存儲和傳遞的都是unicode編碼數(shù)據(jù)
String key = "你好恩";String key1 = new String(key.getBytes("UTF-8"), "gbk");System.out.println(key1);String key2 = new String(key1.getBytes("gbk"), "UTF-8");System.out.println(key2);
###15.按行讀文件&string多個空格切分
File file = new File("d:\\date\\school_beijing.txt");List<String> lines = null;try {lines = Files.readLines(file, Charsets.UTF_8);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}for (String line : lines) {String name = line.split("\\s+")[1];System.out.print("('" + name + "',1),");}###16.取[min,max]范圍的隨機數(shù)
int s = random.nextInt(max)%(max-min+1) + min;其中,random.nextInt(max)表示生成[0,max]之間的隨機數(shù)
###17.guava joiner:給字符串每一個中間插入'%'
String result = Joiner.on("%").join(Chars.asList(name.toCharArray()));###18.把對象和map互相轉(zhuǎn)化
-
BeanUtils.describe:會把對象中的變量都轉(zhuǎn)化成string
User user = …;Map userMap = BeanUtils.describe(user);//Map userMap = …;User user = …;BeanUtils.populate(user,userMap); -
PropertyUtils.describe:變量是啥就是啥,因此轉(zhuǎn)化成mybatis的參數(shù)時用這個
###19.powermock靜態(tài)方法 testng ####1.靜態(tài)方法,假設(shè)是個工具類:
public class Util {public static int getInt() {return 1;} }####2.被測試類Target
public class Target {public int findInt() {int key = Util.getInt();return key;} }####3.測試類
import org.mockito.InjectMocks;import org.mockito.MockitoAnnotations;import org.powermock.api.mockito.PowerMockito;import org.powermock.core.classloader.annotations.PrepareForTest;import org.testng.Assert;import org.testng.annotations.BeforeClass;import org.testng.annotations.Test;@PrepareForTest({ Util.class })public class TargetTest {@InjectMocksprivate Target target;@BeforeClasspublic void setUp() {this.target = new Target();MockitoAnnotations.initMocks(this);}@Testpublic void targetTest() throws Exception {PowerMockito.mockStatic(Util.class);PowerMockito.doReturn(1).when(Util.class, "getInt");//如果有參數(shù)加到when()后面int key = target.findInt();Assert.assertEquals(1, key);}}###20.數(shù)組初始化與打印
int[] keys = { 1, 2, 3, 4, 5 };int[] ones = new int[10];int[] two = new int[] { 1, 2, 3, 4 };System.out.println(Arrays.toString(keys));###21.list移除元素:
使用iterator,因為list.remove()會改變size
public <T> void removeElement(List<T> list,T element){Iterator<T> iterator=list.iterator();while (iterator.hasNext()) {T t = (T) iterator.next();if (t.equals(element)){iterator.remove();}} }###22.判斷字符串字符集:
沒有方法可以直接判斷出來,只能看它是否是某個字符集:
if(key.equals(new String(key.getBytes("utf-8"), "utf-8"))){System.out.println("it is utf-8"); }
###23.string轉(zhuǎn)list<Long>("123,456,124")
List<Long> longs = Lists.newArrayList(Iterables.transform(Splitter.on(',').split("1,2,3"), new Function<String, Long>() { public Long apply(final String in) {return in == null ? null : Longs.tryParse(in); } }));###24.bigdecimal避免輸出科學(xué)計數(shù)法:
return a.toPlainString()###25.數(shù)組,列表互轉(zhuǎn)
-
數(shù)組轉(zhuǎn)列表
String[] arr = {"a", "b", "c"};List<String> list = Arrays.asList(arr); -
列表轉(zhuǎn)數(shù)組
String[] arr1=list.toArray(new String[list.size()]);
###26.guava讀取文件流
private String readInputStream(InputStream in) throws IOException {return CharStreams.toString(new InputStreamReader(in));}轉(zhuǎn)載于:https://my.oschina.net/SearchVera/blog/493471
總結(jié)
- 上一篇: 修真江湖2轮回井攻略
- 下一篇: ViewPager实现页面切换