java操作
java操作
Scofieldxs 发表于3年前
java操作
  • 发表于 3年前
  • 阅读 160
  • 收藏 5
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

###1.list转map(将某一列作为key)

final ImmutableMap<Long, Position> indexPosition = Maps.uniqueIndex(
            positionList, new Function<Position, Long>() {
                @Override
                public 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.带查找和排序的类设计

public class DemoVo {
    private Integer id;
    private String name;
    private Integer curPage;//当前页码
    private Integer pageSize;//分页大小
    private Integer offset;//数据偏移量
    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;
    /**
     * 默认当前页码
     */
    public static final int DEFAULT_CURPAGE = 1;
    /**
     * 默认排序
     */
    public static final String DEFAULT_SORTBY = "name";
    /**
     * 默认排序方式
     */
    public static final String DEFAULT_ORDERBY = "asc";
}
  • 排序设置方法

      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 stub
			return arg0.getName();
		}
	});
	
	System.out.println(Joiner.on(",").join(names));
}

###9.httpclient post带参数

	//url及参数
	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 exception
        log.info("fengchao http error" + url, e);
    } finally {
        post.releaseConnection();
    }

###10.数据库表结构相同的两个表,java端赋值实体:

App app=new App();
AppHis appHis=new AppHis();
BeanUtils.copyProperties(appHis, app);

###11.CaseFormat做字符转换

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无法直接传入列表,将数据传给string,重写列表的get方法,用gson自己解

  • gson可以用来在json和对象间转换,json和泛型list转换:

      Dormitory dormitory = new Dormitory();
      dormitory.setId(1L);
      dormitory.setName("haha");
    
      // 类转json
      Gson gson = new Gson();
      String key = gson.toJson(dormitory);
    
      System.out.println(key);
    
      // json转类
      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.编码格式转换

  • unicode是一种编码规范,UTF-8属于规范的一种实现。

  • 无论哪种格式,存储和传递的都是unicode编码数据

      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 block
            e.printStackTrace();
        }

        for (String line : lines) {
            String name = line.split("\\s+")[1];
            System.out.print("('" + name + "',1),");
        }

###16.取[min,max]范围的随机数

    int s = random.nextInt(max)%(max-min+1) + min;

其中,random.nextInt(max)表示生成[0,max]之间的随机数

###17.guava joiner:给字符串每一个中间插入'%'

    String result = Joiner.on("%").join(Chars.asList(name.toCharArray()));

###18.把对象和map互相转化

  • BeanUtils.describe:会把对象中的变量都转化成string

      User user = …;
      Map userMap = BeanUtils.describe(user);
      //////////////
      Map userMap = …;
      User user = …;
      BeanUtils.populate(user,userMap);
    
  • PropertyUtils.describe:变量是啥就是啥,因此转化成mybatis的参数时用这个

###19.powermock静态方法 testng ####1.静态方法,假设是个工具类:

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 {
	
	    @InjectMocks
	    private Target target;
	
	    @BeforeClass
	    public void setUp() {
	        this.target = new Target();
	        MockitoAnnotations.initMocks(this);
	    }
	
	    @Test
	    public void targetTest() throws Exception {
	        PowerMockito.mockStatic(Util.class);
	        PowerMockito.doReturn(1).when(Util.class, "getInt");
			//如果有参数加到when()后面
	        int key = target.findInt();
	        Assert.assertEquals(1, key);
	    }
	}

###20.数组初始化与打印

    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转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避免输出科学计数法:

    return a.toPlainString()

###25.数组,列表互转

  • 数组转列表

      String[] arr = {"a", "b", "c"};
      List<String> list = Arrays.asList(arr);
    
  • 列表转数组

      String[] arr1=list.toArray(new String[list.size()]);
    

###26.guava读取文件流

    private String readInputStream(InputStream in) throws IOException {

        return CharStreams.toString(new InputStreamReader(in));
    }
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 3
博文 24
码字总数 26447
×
Scofieldxs
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: