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))
Answer from Priyank Doshi on Stack OverflowRegarding 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 ";
}
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.
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()
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.)