一:三元运算符
条件表达式 ? 取值1 :取值2
三元运算符是if else或者if else if else的简写形式,可以使代码看起来简洁些。
private String ternary1(int first){ System.out.println("==============================================================================================================="); System.out.println("====三元运算符:if else的模式====="); System.out.println("====first=1时返回已售; ====="); System.out.println("====first!=1时返回未售; ====="); String str=first==1?"已售":"未售"; System.out.println("first="+first+",返回:"+str); return str; } private String ternary2(int first,int second){ System.out.println("==============================================================================================================="); System.out.println("====三元运算符:if else if else的模式====="); System.out.println("====first=1,且second=1时返回 再售; ====="); System.out.println("====first=1,且second!=1时返回 已售; ====="); System.out.println("====其它情况时返回 未售; ====="); String str=first==1?(second==1?"再售":"已售"):"未售"; System.out.println("first="+first+",second="+second+",返回:"+str); return str; }
二:foreach操作 for(集合中元素的类型或者数组中元素的类型 表示元素的变量 : 数组或者集合的变量或者表达式){}
java在jdk1.5中开始支持foreach循环,foreach在一定程度上简化了对数组、集合的遍历。
- 需要使用索引的地方还是需要用for循环。
- foreach只能遍历实现了Iterable接口的集合,例如Collection集合,不能直接遍历Map集合,可以通过遍历map.entrySet遍历Map集合。
- 在用foreach循环遍历一个集合时不能向集合中增加元素,不能从集合中删除元素,否则会抛出ConcurrentModificationException异常。
- 遍历LinkedList时,foreach遍历的效率高些,在遍历数组和其它集合时二者效率相当。
- foreach是一个语法糖(就是通过编译器或者其它手段优化了代码,给使用带来了便利)。foreach在处理集合时,实际上通过迭代器进行处理的(如下所示),在处理数组是是通过普通的for循环处理的。
Iterator<String> iterator=collection.iterator(); while(iterator.hasNext()){ System.out.println("迭代=="+iterator.next()); }
三:java8中配合lambda表达式的forEach
collection.forEach(s -> { System.out.println(s); });
自定义Consumer<T>类进行迭代
private class MyConsumer implements Consumer<Object>{ @Override public void accept(Object o) { System.out.println("打印输出(动作执行的参数):" + o); } } private void forEach6(){ System.out.println("============遍历ArrayList java8 foreach方法============================"); Collection<String> collection=new ArrayList<>(5); for (int i = 0; i <5 ; i++) { ((ArrayList<String>) collection).add(i,(i+1)+""); } collection.forEach(new MyConsumer()); }
对Map集合的遍历如下所示:
private void forEach7(){ System.out.println("============遍历HashMap,不能直接遍历Map============================"); Map<String,String> map=new HashMap<>(5); for (int i = 0; i <5 ; i++) { map.put(i+"",i+1+""); } System.out.println("普通方法遍历Map"); //其实是在遍历Set集合 for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key : " + entry.getKey() + " value : " + entry.getValue()); } System.out.println("java8 lambda遍历Map"); map.forEach((k,v)->{ System.out.println("key:"+k+",value:"+v); }); }