- 浏览: 93874 次
- 性别:
- 来自: 广州
文章分类
最新评论
-
zsl131:
问题分析得很好,要是要具体的解决办法就好了!!很期待!!!
JVM崩溃原因 -
niuka:
哈哈,浏览了你的帖子,复习了spring的Aop,谢谢了!
一个简单的Spring的AOP例子(转) -
zhhfzsw:
SELECT DATEDIFF(day,'2008-12-9' ...
SQL Server DATEDIFF() 函数 -
mfhappy:
楼主:SELECT DATEDIFF(day,'2008-12 ...
SQL Server DATEDIFF() 函数
自:http://macrochen.iteye.com/blog/737058
参考:
http://codemunchies.com/2009/10/beautiful-code-with-google-collections-guava-and-static-imports-part-1/ (2,3,4)
http://blog.publicobject.com
更多用法参考http://ajoo.iteye.com/category/119082
以前这么用:
Map<String, Map<Long, List<String>>> map = new HashMap<String, Map<Long,List<String>>>();
现在这么用(JDK7将实现该功能):
Map<String, Map<Long, List<String>>> map = Maps.newHashMap();
针对不可变集合:
以前这么用:
- List<String> list = new ArrayList<String>();
- list.add("a");
- list.add("b");
- list.add("c");
- list.add("d");
List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d");
现在Guava这么用:
- ImmutableList<String> of = ImmutableList.of("a", "b", "c", "d");
- ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");
ImmutableList<String> of = ImmutableList.of("a", "b", "c", "d"); ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");
文本文件读取现在Guava这么用
- File file = new File(getClass().getResource("/test.txt").getFile());
- List<String> lines = null;
- try {
- lines = Files.readLines(file, Charsets.UTF_8);
- } catch (IOException e) {
- e.printStackTrace();
- }
File file = new File(getClass().getResource("/test.txt").getFile()); List<String> lines = null; try { lines = Files.readLines(file, Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); }
基本类型比较, 现在Guava这么用:
int compare = Ints.compare(a, b);
Guava中CharMatcher的用法:
- assertEquals("89983", CharMatcher.DIGIT.retainFrom("some text 89983 and more"))
- assertEquals("some text and more", CharMatcher.DIGIT.removeFrom("some text 89983 and more"))
assertEquals("89983", CharMatcher.DIGIT.retainFrom("some text 89983 and more")) assertEquals("some text and more", CharMatcher.DIGIT.removeFrom("some text 89983 and more"))
Guava中Joiner的用法:
- int[] numbers = { 1, 2, 3, 4, 5 };
- String numbersAsString = Joiner.on(";").join(Ints.asList(numbers));
int[] numbers = { 1, 2, 3, 4, 5 }; String numbersAsString = Joiner.on(";").join(Ints.asList(numbers));
另一种写法:
String numbersAsStringDirectly = Ints.join(";", numbers);
Guava中Splitter的用法:
Iterable split = Splitter.on(",").split(numbsAsString);
对于这样的字符串进行切分:
- String testString = "foo , what,,,more,";
- Iterable<String> split = Splitter.on(",").omitEmptyStrings().trimResults().split(testString);
String testString = "foo , what,,,more,"; Iterable<String> split = Splitter.on(",").omitEmptyStrings().trimResults().split(testString);
Ints中一些用法:
- int[] array = { 1, 2, 3, 4, 5 };
- int a = 4;
- boolean contains = Ints.contains(array, a);
- int indexOf = Ints.indexOf(array, a);
- int max = Ints.max(array);
- int min = Ints.min(array);
- int[] concat = Ints.concat(array, array2);
int[] array = { 1, 2, 3, 4, 5 }; int a = 4; boolean contains = Ints.contains(array, a); int indexOf = Ints.indexOf(array, a); int max = Ints.max(array); int min = Ints.min(array); int[] concat = Ints.concat(array, array2);
集合
set的交集, 并集, 差集的用法(http://publicobject.com/2008/08/coding-in-small-with-google-collections.html)
- HashSet setA = newHashSet(1, 2, 3, 4, 5);
- HashSet setB = newHashSet(4, 5, 6, 7, 8);
- SetView union = Sets.union(setA, setB);
- System.out.println("union:");
- for (Integer integer : union)
- System.out.println(integer);
- SetView difference = Sets.difference(setA, setB);
- System.out.println("difference:");
- for (Integer integer : difference)
- System.out.println(integer);
- SetView intersection = Sets.intersection(setA, setB);
- System.out.println("intersection:");
- for (Integer integer : intersection)
- System.out.println(integer);
HashSet setA = newHashSet(1, 2, 3, 4, 5); HashSet setB = newHashSet(4, 5, 6, 7, 8); SetView union = Sets.union(setA, setB); System.out.println("union:"); for (Integer integer : union) System.out.println(integer); SetView difference = Sets.difference(setA, setB); System.out.println("difference:"); for (Integer integer : difference) System.out.println(integer); SetView intersection = Sets.intersection(setA, setB); System.out.println("intersection:"); for (Integer integer : intersection) System.out.println(integer);
针对Map的用法:
- MapDifference differenceMap = Maps.difference(mapA, mapB);
- differenceMap.areEqual();
- Map entriesDiffering = differenceMap.entriesDiffering();
- Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();
- Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();
- Map entriesInCommon = differenceMap.entriesInCommon();
MapDifference differenceMap = Maps.difference(mapA, mapB); differenceMap.areEqual(); Map entriesDiffering = differenceMap.entriesDiffering(); Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft(); Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight(); Map entriesInCommon = differenceMap.entriesInCommon();
验证与条件检查
原来的写法:
if (count <= 0) { throw new IllegalArgumentException("must be positive: " + count); }
Guava的写法(Jakarta Commons中有类似的方法):
Preconditions.checkArgument(count > 0, "must be positive: %s", count);
一个更酷的用法:
- public PostExample(final String title, final Date date, final String author) {
- this.title = checkNotNull(title);
- this.date = checkNotNull(date);
- this.author = checkNotNull(author);
- }
public PostExample(final String title, final Date date, final String author) { this.title = checkNotNull(title); this.date = checkNotNull(date); this.author = checkNotNull(author); }
如果一个key对应多个value的Map, 你会怎么处理? 如果还在使用Map<K, List<V>>的话, 你就out了
使用MultiMap吧:
Multimap<Person, BlogPost> multimap = ArrayListMultimap.create();
Multimap的另一个使用场景:
比如有一个文章数据的map:
List<Map<String, String>> listOfMaps = mapOf("type", "blog", "id", "292", "author", "john");
如果要按照type分组生成一个List
- Multimap<String, Map<String, String>> partitionedMap = Multimaps.index(
- listOfMaps,
- new Function<Map<String, String>, String>() {
- public String apply(final Map<String, String> from) {
- return from.get("type");
- }
- });
Multimap<String, Map<String, String>> partitionedMap = Multimaps.index( listOfMaps, new Function<Map<String, String>, String>() { public String apply(final Map<String, String> from) { return from.get("type"); } });
针对集合中只有一个元素的情况:
Iterables.getOnlyElement();
这个主要是用来替换Set.iterator.next()或 List.get(0), 而且在测试中使用非常方便, 如果出现0个或者2+则直接抛出异常
比较的最大最小值:
Comparators.max
Comparators.min
equals和hashcode的用法:
- public boolean equals(Object o) {
- if (o instanceof Order) {
- Order that = (Order)o;
- return Objects.equal(address, that.address)
- && Objects.equal(targetArrivalDate, that.targetArrivalDate)
- && Objects.equal(lineItems, that.lineItems);
- } else {
- return false;
- }
- }
- public int hashCode() {
- return Objects.hashCode(address, targetArrivalDate, lineItems);
- }
public boolean equals(Object o) { if (o instanceof Order) { Order that = (Order)o; return Objects.equal(address, that.address) && Objects.equal(targetArrivalDate, that.targetArrivalDate) && Objects.equal(lineItems, that.lineItems); } else { return false; } } public int hashCode() { return Objects.hashCode(address, targetArrivalDate, lineItems); }
ImmutableList.copyOf的用法:
以前这么用:
- public Directions(Address from, Address to, List<Step> steps) {
- this.from = from;
- this.to = to;
- this.steps = Collections.unmodifiableList(new ArrayList<Step>(steps));
- }
public Directions(Address from, Address to, List<Step> steps) { this.from = from; this.to = to; this.steps = Collections.unmodifiableList(new ArrayList<Step>(steps)); }
现在这么用:
- public Directions(Address from, Address to, List<Step> steps) {
- this.from = from;
- this.to = to;
- this.steps = ImmutableList.of(steps);
- }
public Directions(Address from, Address to, List<Step> steps) { this.from = from; this.to = to; this.steps = ImmutableList.of(steps); }
Iterables.concat()的用法:
以前这么用:
- public boolean orderContains(Product product) {
- List<LineItem> allLineItems = new ArrayList<LineItem>();
- allLineItems.addAll(getPurchasedItems());
- allLineItems.addAll(getFreeItems());
- for (LineItem lineItem : allLineItems) {
- if (lineItem.getProduct() == product) {
- return true;
- }
- }
- return false;
- }
public boolean orderContains(Product product) { List<LineItem> allLineItems = new ArrayList<LineItem>(); allLineItems.addAll(getPurchasedItems()); allLineItems.addAll(getFreeItems()); for (LineItem lineItem : allLineItems) { if (lineItem.getProduct() == product) { return true; } } return false; }
现在这么用:
- public boolean orderContains(Product product) {
- for (LineItem lineItem : Iterables.concat(getPurchasedItems(), getFreeItems())) {
- if (lineItem.getProduct() == product) {
- return true;
- }
- }
- return false;
- }
public boolean orderContains(Product product) { for (LineItem lineItem : Iterables.concat(getPurchasedItems(), getFreeItems())) { if (lineItem.getProduct() == product) { return true; } } return false; }
Constraints.constrainedList: 给List操作注入约束逻辑, 比如添加不合法元素直接报错.
以前这么写:
- private final List<LineItem> purchases = new ArrayList<LineItem>();
- /**
- * Don't modify this! Instead, call {@link #addPurchase(LineItem)} to add
- * new purchases to this order.
- */
- public List<LineItem> getPurchases() {
- return Collections.unmodifiableList(purchases);
- }
- public void addPurchase(LineItem purchase) {
- Preconditions.checkState(catalog.isOffered(getAddress(), purchase.getProduct()));
- Preconditions.checkState(purchase.getCharge().getUnits() > 0);
- purchases.add(purchase);
- }
- 这么写:
- private final List<LineItem> purchases = Constraints.constrainedList(
- new ArrayList<LineItem>(),
- new Constraint<LineItem>() {
- public void checkElement(LineItem element) {
- Preconditions.checkState(catalog.isOffered(getAddress(), element.getProduct()));
- Preconditions.checkState(element.getCharge().getUnits() > 0);
- }
- });
- /**
- * Returns the modifiable list of purchases in this order.
- */
- public List<LineItem> getPurchases() {
- return purchases;
- }
private final List<LineItem> purchases = new ArrayList<LineItem>(); /** * Don't modify this! Instead, call {@link #addPurchase(LineItem)} to add * new purchases to this order. */ public List<LineItem> getPurchases() { return Collections.unmodifiableList(purchases); } public void addPurchase(LineItem purchase) { Preconditions.checkState(catalog.isOffered(getAddress(), purchase.getProduct())); Preconditions.checkState(purchase.getCharge().getUnits() > 0); purchases.add(purchase); } 现在这么写: private final List<LineItem> purchases = Constraints.constrainedList( new ArrayList<LineItem>(), new Constraint<LineItem>() { public void checkElement(LineItem element) { Preconditions.checkState(catalog.isOffered(getAddress(), element.getProduct())); Preconditions.checkState(element.getCharge().getUnits() > 0); } }); /** * Returns the modifiable list of purchases in this order. */ public List<LineItem> getPurchases() { return purchases; }
不允许插入空值的Set(Constraints的用法):
- Set<String> set = Sets.newHashSet();
- Set<String> constrainedSet = Constraints.constrainedSet(set, Constraints.notNull());
- constrainedSet.add("A");
- constrainedSet.add(null); // NullPointerException here
Set<String> set = Sets.newHashSet(); Set<String> constrainedSet = Constraints.constrainedSet(set, Constraints.notNull()); constrainedSet.add("A"); constrainedSet.add(null); // NullPointerException here
Multimap的用法(允许多值的map):
以前这么写:
- Map<Salesperson, List<Sale>> map = new Hashmap<SalesPerson, List<Sale>>();
- public void makeSale(Salesperson salesPerson, Sale sale) {
- List<Sale> sales = map.get(salesPerson);
- if (sales == null) {
- sales = new ArrayList<Sale>();
- map.put(salesPerson, sales);
- }
- sales.add(sale);
- }
Map<Salesperson, List<Sale>> map = new Hashmap<SalesPerson, List<Sale>>(); public void makeSale(Salesperson salesPerson, Sale sale) { List<Sale> sales = map.get(salesPerson); if (sales == null) { sales = new ArrayList<Sale>(); map.put(salesPerson, sales); } sales.add(sale); }
现在这么写:
- Multimap<Salesperson, Sale> multimap
- = new ArrayListMultimap<Salesperson,Sale>();
- public void makeSale(Salesperson salesPerson, Sale sale) {
- multimap.put(salesperson, sale);
- }
Multimap<Salesperson, Sale> multimap = new ArrayListMultimap<Salesperson,Sale>(); public void makeSale(Salesperson salesPerson, Sale sale) { multimap.put(salesperson, sale); }
以前这么写:
- public Sale getBiggestSale() {
- Sale biggestSale = null;
- for (List<Sale> sales : map.values()) {
- Sale biggestSaleForSalesman
- = Collections.max(sales, SALE_COST_COMPARATOR);
- if (biggestSale == null
- || biggestSaleForSalesman.getCharge() > biggestSale().getCharge()) {
- biggestSale = biggestSaleForSalesman;
- }
- }
- return biggestSale;
- }
public Sale getBiggestSale() { Sale biggestSale = null; for (List<Sale> sales : map.values()) { Sale biggestSaleForSalesman = Collections.max(sales, SALE_COST_COMPARATOR); if (biggestSale == null || biggestSaleForSalesman.getCharge() > biggestSale().getCharge()) { biggestSale = biggestSaleForSalesman; } } return biggestSale; }
现在这么写(需要将map转换成multimap):
- public Sale getBiggestSale() {
- return Collections.max(multimap.values(), SALE_COST_COMPARATOR);
- }
public Sale getBiggestSale() { return Collections.max(multimap.values(), SALE_COST_COMPARATOR); }
Joiner的用法:
以前这样写:
- public class ShoppingList {
- private List<Item> items = ...;
- ...
- public String toString() {
- StringBuilder stringBuilder = new StringBuilder();
- for (Iterator<Item> s = items.iterator(); s.hasNext(); ) {
- stringBuilder.append(s.next());
- if (s.hasNext()) {
- stringBuilder.append(" and ");
- }
- }
- return stringBuilder.toString();
- }
- }
public class ShoppingList { private List<Item> items = ...; ... public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (Iterator<Item> s = items.iterator(); s.hasNext(); ) { stringBuilder.append(s.next()); if (s.hasNext()) { stringBuilder.append(" and "); } } return stringBuilder.toString(); } }
现在这样写:
- public class ShoppingList {
- private List<Item> items = ...;
- ...
- public String toString() {
- return Join.join(" and ", items);
- }
- }
public class ShoppingList { private List<Item> items = ...; ... public String toString() { return Join.join(" and ", items); } }
Comparators.fromFunction的用法:
以前这样写:
- public Comparator<Product> createRetailPriceComparator(
- final CurrencyConverter currencyConverter) {
- return new Comparator<Product>() {
- public int compare(Product a, Product b) {
- return getRetailPriceInUsd(a).compareTo(getRetailPriceInUsd(b));
- }
- public Money getRetailPriceInUsd(Product product) {
- Money retailPrice = product.getRetailPrice();
- return retailPrice.getCurrency() == CurrencyCode.USD
- ? retailPrice
- : currencyConverter.convert(retailPrice, CurrencyCode.USD);
- }
- };
- }
public Comparator<Product> createRetailPriceComparator( final CurrencyConverter currencyConverter) { return new Comparator<Product>() { public int compare(Product a, Product b) { return getRetailPriceInUsd(a).compareTo(getRetailPriceInUsd(b)); } public Money getRetailPriceInUsd(Product product) { Money retailPrice = product.getRetailPrice(); return retailPrice.getCurrency() == CurrencyCode.USD ? retailPrice : currencyConverter.convert(retailPrice, CurrencyCode.USD); } }; }
现在这样写(感觉也没省多少):
- public Comparator<Product> createRetailPriceComparator(
- final CurrencyConverter currencyConverter) {
- return Comparators.fromFunction(new Function<Product,Money>() {
- /** returns the retail price in USD */
- public Money apply(Product product) {
- Money retailPrice = product.getRetailPrice();
- return retailPrice.getCurrency() == CurrencyCode.USD
- ? retailPrice
- : currencyConverter.convert(retailPrice, CurrencyCode.USD);
- }
- });
- }
public Comparator<Product> createRetailPriceComparator( final CurrencyConverter currencyConverter) { return Comparators.fromFunction(new Function<Product,Money>() { /** returns the retail price in USD */ public Money apply(Product product) { Money retailPrice = product.getRetailPrice(); return retailPrice.getCurrency() == CurrencyCode.USD ? retailPrice : currencyConverter.convert(retailPrice, CurrencyCode.USD); } }); }
BiMap(双向map)的用法:
以前的用法:
- private static final Map<Integer, String> NUMBER_TO_NAME;
- private static final Map<String, Integer> NAME_TO_NUMBER;
- static {
- NUMBER_TO_NAME = Maps.newHashMap();
- NUMBER_TO_NAME.put(1, "Hydrogen");
- NUMBER_TO_NAME.put(2, "Helium");
- NUMBER_TO_NAME.put(3, "Lithium");
- /* reverse the map programatically so the actual mapping is not repeated */
- NAME_TO_NUMBER = Maps.newHashMap();
- for (Integer number : NUMBER_TO_NAME.keySet()) {
- NAME_TO_NUMBER.put(NUMBER_TO_NAME.get(number), number);
- }
- }
- public static int getElementNumber(String elementName) {
- return NUMBER_TO_NAME.get(elementName);
- }
- public static string getElementName(int elementNumber) {
- return NAME_TO_NUMBER.get(elementNumber);
- }
private static final Map<Integer, String> NUMBER_TO_NAME; private static final Map<String, Integer> NAME_TO_NUMBER; static { NUMBER_TO_NAME = Maps.newHashMap(); NUMBER_TO_NAME.put(1, "Hydrogen"); NUMBER_TO_NAME.put(2, "Helium"); NUMBER_TO_NAME.put(3, "Lithium"); /* reverse the map programatically so the actual mapping is not repeated */ NAME_TO_NUMBER = Maps.newHashMap(); for (Integer number : NUMBER_TO_NAME.keySet()) { NAME_TO_NUMBER.put(NUMBER_TO_NAME.get(number), number); } } public static int getElementNumber(String elementName) { return NUMBER_TO_NAME.get(elementName); } public static string getElementName(int elementNumber) { return NAME_TO_NUMBER.get(elementNumber); }
现在的用法:
- private static final BiMap<Integer,String> NUMBER_TO_NAME_BIMAP;
- static {
- NUMBER_TO_NAME_BIMAP = Maps.newHashBiMap();
- NUMBER_TO_NAME_BIMAP.put(1, "Hydrogen");
- NUMBER_TO_NAME_BIMAP.put(2, "Helium");
- NUMBER_TO_NAME_BIMAP.put(3, "Lithium");
- }
-
public static </
发表评论
相关推荐
12. **Java库与框架**:可能包含使用Apache Commons、Google Guava等常用库,以及Spring、Hibernate等框架的示例,帮助开发者更好地理解和应用这些工具。 13. **异常处理**:Java异常处理是程序错误处理的关键,...
2. Guava:Google推出的高效库,包含集合、缓存、并发、I/O等多方面工具,尤其在处理并发和数据结构方面有显著优势。 3. Lombok:一个可以通过注解自动为类生成getter、setter、构造函数等元数据的库,减少了样板...
Java常用工具类整理 本文将详细介绍 Spring 及 Guava 相关工具类的使用说明和代码 demo。这些工具类都是 Java 开发中常用的实用工具,可以帮助开发者快速高效地完成各种任务。 一、Spring 工具类 1. org.spring...
OTTO是Google Guava团队开发的一个轻量级事件总线框架,它主要用于Android应用程序中的组件解耦。在“OTTO官方demo整理工程”中,我们可以深入理解如何在实际项目中运用OTTO框架来提高代码的可维护性和灵活性。 ...
11. **Guava**: Guava 是Google提供的一个Java库,包含了大量的系统级别的实用工具类,如集合、并发、缓存、I/O等。 12. **JUnit.jupiter**: 这是JUnit 5的新测试引擎,提供了更现代的测试API和更灵活的测试配置。 ...
此外,可能还包括Spring Framework、Hibernate ORM等框架的官方文档,以及Apache Commons、Guava等常用库的API。 2. **在线编译器与运行平台**:例如CodePen、Repl.it或Jsfiddle,这些平台可以让开发者在浏览器中...
13. **Java API和库**:介绍常用API,如Math、Date、Calendar,以及第三方库如Apache Commons或Google Guava的使用。 14. **设计模式**:可能涵盖了单例、工厂、观察者、装饰器等常见设计模式的概念和应用场景。 ...
- **Guava**:Google提供的Java库,包含大量常用的工具类和数据结构。 9. **面试准备** - **集合框架**:深入理解集合类的特性,如ArrayList与LinkedList的性能差异,以及在多线程环境下的选择。 - **IO框架**:...
9. **Google Guava**:guava.jar,提供了许多Java核心库的高级功能,如集合操作、并发工具、I/O操作等。 10. **Jackson或Gson**:如jackson-databind.jar,用于JSON对象与Java对象之间的相互转换。 以上只是列举了...
2. Guava:Google的工具库,包含丰富的数据结构、并发工具、缓存机制等。 以上只是Java编程的一部分知识点,实际开发中还需要理解设计模式、数据库操作、框架应用、测试技巧等多个方面。不断学习和实践,才能真正...
例如,`log4j.jar`用于日志记录,`slf4j-api.jar`和相应的实现库用于更高级的日志抽象,`commons-lang3.jar`提供了很多实用的工具类,`guava.jar`是Google提供的大量常用工具类库。 在实际开发中,根据项目需求,...
- **Glide**:Google推荐的图片加载库,特别适合于处理大量的图片加载,支持多种资源格式和高效的内存管理。 3. **图片处理** - **Picasso-transformations**:为Picasso提供了一系列的图片变换效果,如圆形、...
- **Google Guava**:`com.google.common.io.BaseEncoding.base64()` - **net.iharder.Base64** - **MigBase64**:据称是编码速度最快的实现 为了评估不同实现的性能,可以通过编写性能测试代码,对比它们在大量...