Iterator iterator = c.iterator();
public boolean hasNext()public Object next(). next() method throws 1 exception. NoSuchElementException β> if no more element is present.public void remove(). Remove() method throws 2 exceptions. UnsupportedOperationException β> if remove operation is not supported by this Iterator. IllegalStateException β> if next method has not yet been called or remove method has already been called after the last call to the next method.public class I1Intro {
public static void main(String ...args) {
List<Integer> numbers = List.of(1,2,3,4,5,6);//Arrays.asList()
Integer sum = 0;//Integer.MIN_VALUE;
//Declarative Style === what to do, delegate how to do to Java
int sumTotal = numbers.stream().parallel()
.mapToInt(number -> number)
.sum();
System.out.println(sumTotal);
}
}
public class Iterators {
private static List<String> forLoopWithVar(List<String> list, int count) {
var ret = new ArrayList<String>();
var input = list;
int x = 0;
for(var name : list){
var str = name;
if(str.length() > 4){
x++;
ret.add(str.toUpperCase());
}
if(x == count){
break;
}
}
return ret;
}
private static List<String> forLoop(List<String> list, int count) {
//and then
//Imperative style === what to do + how to do + Eager Evaluation
int x = 0;
List<String> ret = new ArrayList<>();
//send first 2 string with lenght > 4
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
if(str.length() > 4){
x++;
ret.add(str.toUpperCase());
}
if(x == count){
break;
}
}
return ret;
}
}
private static List<String> forLoopStreams(List<String> list, int count) {
var ret = new ArrayList<String>();
//Functional Style == declarative style
//Works until now, but stooped all of a sudden
// Code behaves - erratically with parallel Stream
ret = (ArrayList<String>) list.stream().parallel()
//.filter(name -> null != name)
.filter(Objects::nonNull)
.filter(name -> name.length() > 2)
.map(nameInLowerCase -> nameInLowerCase.toUpperCase())
.limit(count)
//.forEach(name -> ret.add(name));//BAD IDEA with ParallelStream - due to shared mutability - this is impure
.collect(Collectors.toList());//Thread safe
return ret;
}
public interface Iterator{
public boolean hasNext();
public Object next();
}
public class Namerepository implements Container{
public String names[] = {"Deepthi", "Nitin", "Keerthi"};
@Override
public Iterator getIterator(){
return new NameIterator();
}
private class NameIterator implements Iterator{
int index = 0;
@Override
public boolean hasNext(){
if(index < names.length){
return true;
}
return false;
}
@Override
public Object next(){
if(this.hasNext()){
return names[index++];
}
return null;
}
}
public class IteratorPtterndemo{
public ststic void main(String[] args){
NameRepository namesRepository = new NameRepository();
for(Iterator iterator = namesRepository.getIterator();
iterator.hasNext();
)
{
String name = (String)iter.next();
System.out.println("Name:"+name);
}
}
}