See the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
Answer from stacker on Stack OverflowSee the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
Collection c;
Iterator iter = c.iterator();
Object first = iter.next();
(This is the closest you'll get to having the "first" element of a Set. You should realize that it has absolutely no meaning for most implementations of Set. This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)
Its always advised to use Iterators or ListIterator to iterate through a list. Using the list size as reference does not workout when you are modifying the list data (removing or inserting elements).
Iterator - allow the caller to iterate through a list in one direction and remove elements from the underlying collection during the iteration with well-defined semantics
You can use a ListIterator to iterate through the list. A ListIterator allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. You can refer the below example.
ArrayList<String> list = new ArrayList<String>();
ListIterator<String> iterator = list.listIterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
...
...
System.out.println(iterator.previous());
if(!iterator.hasPrevious()){
System.out.println("at start of the list");
}else if(!iterator.hasNext()){
System.out.println("at end of the list");
}
}
This is just an example showing the usage of a ListIterator, please analyze what your requirement is and implement as required.
List<YourData> list = new ArrayList<YourData>();
for(int index=0; index < list.size(); index++) {
YourData currElement = list.get(index);
if(index == 0) {
//currElement is the first element
}
if(index == list.size() - 1) {
//currElement is the last element
}
}
The ArrayList has a method size that returns the size of the list, and a get method to get the element stored at a particular index.
So your for loop could look like:
for(int k=0; k < al.size(); k++) {
System.out.println("elements are" + al.get(k));
}
Or if you want you could loop through each element without an index:
for(String text : al) {
System.out.println("elements are" + text);
}
If you want to use streams with java8, you could also do:
al.stream().forEach(System.out::println);
If you are interested, there's another answer that also talks about looping through lists in java.
Since ArrayList is a collection not an array, you may use al.size() instead.
If you want to use index try this
al.get(k)
Regarding the heading of your question:
get first and last element in ArrayList in Java
It should be pretty simple:
mimeList.get(0); // To get first
mimeList.get(mimeList.size()-1); //to get last
And regarding your if condition :
if(!(i==0 || i==mimeList.size()-1))
As you phrased it like:
if the element in mimeList is first or last it will go in else condition other wise in if condition
I used ! in if condition.
Otherwise below is pretty cool:
if((i>0) && (i!=mimeList.size()-1))
A simpler way to do with without lots of checks is to use seperator which is empty to start with.
StringBuilder sb = new StringBuilder();
String sep = "";
for (String s : mimeList) {
sb.append(sep + key + "=" + s);
sep = " or ";
}
You should take a look at this answer because this is exactly what you want: https://stackoverflow.com/a/8882358/9016740
You can access the first element of an ArrayList by using the get(index) method as such:
List<String> resultList = new ArrayList<String>();
List<Object[]> listObj = (List<Object[]>)query.getResultList();
Object[] firstObjArray = listObj.get(0);
resultList.add(((String)firstObjArray[0]));
resultList.add(((String)firstObjArray[1]));
Try this.
Object[] resultArr = listObj.get(0);
Now use resultArr to fetch values and store in resultList.
One way is to use a Stream and map each of the inner arrays to its first element:
List<String> firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.collect(Collectors.toList());
If you would like an array of strings instead:
String[] firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.toArray(String[]::new);
I also suggest you to not use nested arrays like this. You should create a class with the properties you want to store and create a List of your class.
As I suppose the first entry is unique (as it seems to be a username), I would suggest using a Map. That way, you could simply list the keys.
HashMap<String,ArrayList<String>> hashmap=new HashMap<>();
Alternatively, you could simply create a class containing that information, to avoid needing the use of an ArrayList, but I don't know if this is an option.
Write a Comparator.
Comparator<MyType> myOrder = new Comparator<MyType>() {
public int compare(MyType a, MyType b) {
return (b.booleanField() ? 1 : 0) - (a.booleanField() ? 1 : 0);
}
}
Sort using this comparator.
Collections.sort(myList, myOrder);
See Collections.sort
Edit
So it seems that what you're actually asking for is to move just one matching element to the front of your list. That ought to be pretty easy.
Find the index of the element you want to move:
int foundIndex = -1;
for (int i = 0; i < tripList.size(); ++i) {
if (tripList.get(i).freeCancellation) {
foundIndex = i;
break;
}
}
If you find such an element, and it is not already at the start, move it to the start:
if (foundIndex > 0) {
tripList.add(0, tripList.remove(foundIndex));
}
List<Object> objList = findObj(name);Collections.sort(objList, new Comparator<Object>() {
@Override
public int compare(Object a1, Object a2) {
return (a1.getBooleanField()== a2.getBooleanField())?0:(a1.getBooleanField()?1:-1);
}});
This might help you to resolve this. You modify the results by changing the compare logic