ArrayList searchList = new ArrayList();
ArrayList words=(ArrayList) request.getSession().getAttribute("words");
words.add("one");
words.add("twenty one");
words.add("thirty one");
words.add("two");
words.add("twenty two");
words.add("thirty two");
words.add("three");
words.add("twenty three");
words.add("thirty three");'
If I have this arraylist and I want to search all the strings containing one(i.e. one,twenty one and thirty one), what logic should I use? Means how should I do that?
for (String item : searchList) {
if (item.contains("one") {
// Do something. Like adding the result to a different list.
// If you need the index from the original list, you a for instead of a for each
}
}
//iterate through words
for(String str : list){
//check if word contains the key
if(str.contains(key)){
//add its reference to another resultant list
result.add(str);
}
}
for (String word : words) {
if (word.contains("one")) {
//we have a match
}
}
Of course you have to loop thru the elements. Look for ways to loop thru an ArrayList: that can be indexed or with the
for (x : collect)
notation.
In the loop you have to do some pattern matching. Read String Java API doc for a method.
(Give'em some think food ...)
You could solve this using iterators if the condition will be more complex
public interface IPredicate<T> {
boolean check(T t);
}
public class PredicatIterable<T> implements Iterable<T> {
private final Iterator<T> iterator;
private final IPredicate<T> predicate;
public PredicatIterable(Iterable<T> iterable, IPredicate<T> predicate) {
this.iterator = iterable.iterator();
this.predicate = predicate;
}
#Override
public Iterator<T> iterator() {
return new Iterator<T>() {
T current;
#Override
public boolean hasNext() {
if(iterator.hasNext()) {
T next = iterator.next();
if(predicate.check(next)) {
current = next;
return true;
}
current = null;
}
return false;
}
#Override
public T next() {
return current;
}
#Override
public void remove() {
throw new RuntimeException("Invalid useage of method");
}
};
}
}
To validate more the single predicate you can create also method that is responsible for conuntion or alternative of two IPredicate argument.
In general, when searching an item in a List, the best solution is to sort your List first using Collections.sort() method. Then using the Collections.binarySearch() method, find your element.
In this case your elements are String type that are Comparable and can be sorted alphabetically otherwise you needed to implement Comparable interface for your element class type.
Related
I have an object list that retrieves multiple values from a database, like so:
List<Object> listRequest = daoManager.getLaptopsForRequest(BigInteger.valueOf(itemTransItem.getAssetType().getId()), BigInteger.valueOf(approverId));
The result of which looks like this (printed out on the console, via for each):
{asset_type_id=1, inventory_id=1, from_dt=2015-09-18 18:04:55.77, id=1, asset_id=1, status=1, thru_dt=null}
{asset_type_id=1, inventory_id=1, from_dt=2015-09-18 18:04:55.77, id=2, asset_id=2, status=1, thru_dt=null}
{asset_type_id=1, inventory_id=1, from_dt=2015-09-18 18:04:55.77, id=3, asset_id=3, status=1, thru_dt=null}
What's the quickest and/or most efficient way to get only the object where asset_id = 2, or an array of asset_id (1 and 2), and putting the results in another array?
I contemplated casting each object as a string, and then turning each string into an array (split by the comma), and then turning each item of the array into a further array (or a hashmap) by using the =, but that seems like a long, long, complex way of nested for loops that might fail (see comparing array of assets).
Perhaps there's another quicker / less complex way to do this that I'm missing? Any suggestions? Thanks.
EDIT: For reference, here's the getLaptopsForRequest function:
public List getLaptopsForRequest(BigInteger asset_type_id, BigInteger party_id){
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(laptopsForRequestSql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List forRequest = query.setBigInteger(0, asset_type_id).setBigInteger(1, party_id).list();
return forRequest;
}
It returns a list of the results of the query. As this code has been in place, I'm not allowed to edit it.
A quick and dirty solution would be to match each item against regex ^.*asset_id=([0-9]+).*$.
If what you're getting from that method is indeed a list of Strings containing those JSONs, you could create a model class and use a JSON serializer like GSON or Jackson to read the strings into Java objects, and then you could work with them.
What you are trying to do basically is to filter a list of objects. You could implement the Filter Pattern writing your own Iterator for the list.
Just extends this class to implement your own filter.
public abstract class Filter<T> {
public abstract boolean passes(T object);
public Iterator<T> filter(Iterator<T> iterator) {
return new FilterIterator(iterator);
}
public Iterable<T> filter(Iterable<T> iterable) {
return new Iterable<T>() {
public Iterator<T> iterator() {
return filter(iterable.iterator());
}
};
}
private class FilterIterator implements Iterator<T> {
private Iterator<T> iterator;
private T next;
private FilterIterator(Iterator<T> iterator) {
this.iterator = iterator;
toNext();
}
public boolean hasNext() {
return next != null;
}
public T next() {
if (next == null)
throw new NoSuchElementException();
T returnValue = next;
toNext();
return returnValue;
}
public void remove() {
throw new UnsupportedOperationException();
}
private void toNext() {
next = null;
while (iterator.hasNext()) {
T item = iterator.next();
if (item != null && passes(item)) {
next = item;
break;
}
}
}
}
}
and then use it in this way:
List<MyObject> newList = new ArrayList<MyObject>();
for(MyObject obj : filter.filter(listObjs) ){
newList.add(obj);
}
Assuming your objects have getter et setter methods.
Only the object where asset_id = "2", asset_id here being a string
listRequest.stream().filter(e -> e.getAssetId() == "2" ).toArray();
In java I have this function:
public List<String> seperatekeys(String text) {
String[] keys = text.split("and");
List<String> words = Arrays.asList(keys);
ListIterator<String> iter = words.listIterator();
while (iter.hasNext()) {
String currentWord = iter.next().trim();
if (currentWord.equals("")) {
iter.remove();
} else {
iter.set(currentWord);
}
}
return words;
}
But when I do a remove(), it crashes saying unsupportedoperationerror.
Anyone know how to fix it?
Thanks
The issue is that Arrays#asList() returns an ArrayList implementation that inherits remove() from AbstractList. The implementation of remove() in AbstractList is this:
public E remove(int index) {
throw new UnsupportedOperationException();
}
And because the iterator uses the list's iterator to perform its remove() method, you end up with the exception.
You have a few solutions here. You can either pass the result of Arrays#asList() to an ArrayList constructor:
List<String> words = new ArrayList<>(Arrays.asList(keys));
Now, you can iterate over the resulting List and remove the elements you want.
Or, asMadProgrammer stated, you can take the opposite approach and iterate over the array and add the elements you want to keep:
List<String> words = new ArrayList<>();
for (String s : keys) {
String currentWord = s.trim();
if (!currentWord.equals("")) {
words.add(currentWord);
}
}
So I have a LinkedHashSet , with values say a1, a2, , b, c1, c2
I want to replace, b with x , such that the order of x should be same as order of b.
One obvious way would be
private LinkedHashSet<String> orderedSubstitution(final Set<String> originalOrderedSet, final String oldItem,
final String newItem) {
final LinkedHashSet<String> newOrderedSet = new LinkedHashSet<String>();
// Things we do to maintain order in a linkedHashSet
for (final String stringItem : originalOrderedSet) {
if (stringItem.equals(oldItem)) {
newOrderedSet.add(newItem);
} else {
newOrderedSet.add(stringItem);
}
}
return newOrderedSet;
}
not only this is O(n) i also feel this is not the fastest way. Any better solution ?
NOTE : I HAVE TO use linkedHashMap.
One way to do it would be to use a subclass of LinkedHashSet that has the replacement built in, e.g.:
public class ReplacingLinkedHashSet extends LinkedHashSet<String> {
private final String what;
private final String with;
public ReplacingLinkedHashSet(String what, String with) {
this.what = what;
this.with = with;
}
#Override
public Iterator<String> iterator() {
final Iterator<String> iterator = super.iterator();
return new Iterator<String>() {
#Override
public boolean hasNext() {
return iterator.hasNext();
}
#Override
public String next() {
String next = iterator.next();
return what.equals(next) ? with : next;
}
#Override
public void remove() {
iterator.remove();
}
};
}
}
But that means the replacement would have to be known before you fill the Set.
(Of course you could easily turn this <String> version into a generic one.
Responding to comments:
OK, then there is no way to solve it without a full iteration. You could however just leave the LinkedHashSet untouched and decorate the iterator when retrieving the values.
Create a structure Map
Insert all the string with < String, OrderOfTheString>
Do the insertion of the new String by adding a small Delta after the current string's OrderOfTheString.
Convert Map to LikedHashSet
I know it is complicated but it is definately better when we have linked hash Map of ~1000000 elements and there are about 1000 elements to be inserted.
I'm migrating a piece of code to make use of generics. One argument for doing so is that the for loop is much cleaner than keeping track of indexes, or using an explicit iterator.
In about half the cases, the list (an ArrayList) is being iterated in reverse order by using an index today.
Can someone suggest a cleaner way of doing this (since I dislike the indexed for loop when working with collections), though it does work?
for (int i = nodes.size() - 1; i >= 0; i--) {
final Node each = (Node) nodes.get(i);
...
}
Note: I can't add any new dependencies outside the JDK.
Try this:
// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();
// Add elements to list.
// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());
// Iterate in reverse.
while(li.hasPrevious()) {
System.out.println(li.previous());
}
Guava offers Lists#reverse(List) and ImmutableList#reverse(). As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.
Example
List reversed = ImmutableList.copyOf(myList).reverse();
I don't think it's possible using the for loop syntax. The only thing I can suggest is to do something like:
Collections.reverse(list);
for (Object o : list) {
...
}
... but I wouldn't say this is "cleaner" given that it's going to be less efficient.
Option 1: Have you thought about reversing the List with Collections#reverse() and then using foreach?
Of course, you may also want to refactor your code such that the list is ordered correctly so you don't have to reverse it, which uses extra space/time.
EDIT:
Option 2: Alternatively, could you use a Deque instead of an ArrayList? It will allow you to iterate forwards and backwards
EDIT:
Option 3: As others have suggested, you could write an Iterator that will go through the list in reverse, here is an example:
import java.util.Iterator;
import java.util.List;
public class ReverseIterator<T> implements Iterator<T>, Iterable<T> {
private final List<T> list;
private int position;
public ReverseIterator(List<T> list) {
this.list = list;
this.position = list.size() - 1;
}
#Override
public Iterator<T> iterator() {
return this;
}
#Override
public boolean hasNext() {
return position >= 0;
}
#Override
public T next() {
return list.get(position--);
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
for (String s : new ReverseIterator<String>(list)) {
System.out.println(s);
}
You could use the concrete class LinkedList instead of the general interface List. Then you have a descendingIterator for iterating with the reverse direction.
LinkedList<String > linkedList;
for( Iterator<String > it = linkedList.descendingIterator(); it.hasNext(); ) {
String text = it.next();
}
Don't know why there is no descendingIterator with ArrayList...
This is an old question, but it's lacking a java8-friendly answer. Here are some ways of reverse-iterating the list, with the help of the Streaming API:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 3, 3, 7, 5));
list.stream().forEach(System.out::println); // 1 3 3 7 5
int size = list.size();
ListIterator<Integer> it = list.listIterator(size);
Stream.generate(it::previous).limit(size)
.forEach(System.out::println); // 5 7 3 3 1
ListIterator<Integer> it2 = list.listIterator(size);
Stream.iterate(it2.previous(), i -> it2.previous()).limit(size)
.forEach(System.out::println); // 5 7 3 3 1
// If list is RandomAccess (i.e. an ArrayList)
IntStream.range(0, size).map(i -> size - i - 1).map(list::get)
.forEach(System.out::println); // 5 7 3 3 1
// If list is RandomAccess (i.e. an ArrayList), less efficient due to sorting
IntStream.range(0, size).boxed().sorted(Comparator.reverseOrder())
.map(list::get).forEach(System.out::println); // 5 7 3 3 1
Here is an (untested) implementation of a ReverseIterable. When iterator() is called it creates and returns a private ReverseIterator implementation, which simply maps calls to hasNext() to hasPrevious() and calls to next() are mapped to previous(). It means you could iterate over an ArrayList in reverse as follows:
ArrayList<String> l = ...
for (String s : new ReverseIterable(l)) {
System.err.println(s);
}
Class Definition
public class ReverseIterable<T> implements Iterable<T> {
private static class ReverseIterator<T> implements Iterator {
private final ListIterator<T> it;
public boolean hasNext() {
return it.hasPrevious();
}
public T next() {
return it.previous();
}
public void remove() {
it.remove();
}
}
private final ArrayList<T> l;
public ReverseIterable(ArrayList<T> l) {
this.l = l;
}
public Iterator<T> iterator() {
return new ReverseIterator(l.listIterator(l.size()));
}
}
If the lists are fairly small so that performance is not a real issue, one can use the reverse-metod of the Lists-class in Google Guava. Yields pretty for-each-code, and the original list stays the same. Also, the reversed list is backed by the original list, so any change to the original list will be reflected in the reversed one.
import com.google.common.collect.Lists;
[...]
final List<String> myList = Lists.newArrayList("one", "two", "three");
final List<String> myReverseList = Lists.reverse(myList);
System.out.println(myList);
System.out.println(myReverseList);
myList.add("four");
System.out.println(myList);
System.out.println(myReverseList);
Yields the following result:
[one, two, three]
[three, two, one]
[one, two, three, four]
[four, three, two, one]
Which means that reverse iteration of myList can be written as:
for (final String someString : Lists.reverse(myList)) {
//do something
}
You could use ReverseListIterator from Apache Commons-Collections:
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/iterators/ReverseListIterator.html
Very simple Example:
List<String> list = new ArrayList<String>();
list.add("ravi");
list.add("kant");
list.add("soni");
// Iterate to disply : result will be as --- ravi kant soni
for (String name : list) {
...
}
//Now call this method
Collections.reverse(list);
// iterate and print index wise : result will be as --- soni kant ravi
for (String name : list) {
...
}
To have code which looks like this:
List<Item> items;
...
for (Item item : In.reverse(items))
{
...
}
Put this code into a file called "In.java":
import java.util.*;
public enum In {;
public static final <T> Iterable<T> reverse(final List<T> list) {
return new ListReverseIterable<T>(list);
}
class ListReverseIterable<T> implements Iterable<T> {
private final List<T> mList;
public ListReverseIterable(final List<T> list) {
mList = list;
}
public Iterator<T> iterator() {
return new Iterator<T>() {
final ListIterator<T> it = mList.listIterator(mList.size());
public boolean hasNext() {
return it.hasPrevious();
}
public T next() {
return it.previous();
}
public void remove() {
it.remove();
}
};
}
}
}
Create a custom reverseIterable.
Also found google collections reverse method.
How about using DeQue:
var queue = new ArrayDeque<>(list);
while (!queue.isEmpty()) {
var first = reversed ? queue.removeLast() : queue.removeFirst();
var second = reversed ? queue.peekLast() : queue.peekFirst();
if (second != null) {
//your code goes here
}
}
As has been suggested at least twice, you can use descendingIterator with a Deque, in particular with a LinkedList. If you want to use the for-each loop (i.e., have an Iterable), you can construct and use a wraper like this:
import java.util.*;
public class Main {
public static class ReverseIterating<T> implements Iterable<T> {
private final LinkedList<T> list;
public ReverseIterating(LinkedList<T> list) {
this.list = list;
}
#Override
public Iterator<T> iterator() {
return list.descendingIterator();
}
}
public static void main(String... args) {
LinkedList<String> list = new LinkedList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
for (String s : new ReverseIterating<String>(list)) {
System.out.println(s);
}
}
}
Valid for Java 9+
List<String> strList = List.of("a", "b", "c", "d", "e");
IntStream.iterate(strList.size() - 1, i -> i >= 0, i -> --i)
.mapToObj(strList::get)
.forEach(System.out::println);
Reason : "Don't know why there is no descendingIterator with ArrayList..."
Since array list doesnot keep the list in the same order as data has been added to list. So, never use Arraylist .
Linked list will keep the data in same order of ADD to list.
So , above in my example, i used ArrayList() in order to make user to twist their mind and make them to workout something from their side.
Instead of this
List<String> list = new ArrayList<String>();
USE:
List<String> list = new LinkedList<String>();
list.add("ravi");
list.add("kant");
list.add("soni");
// Iterate to disply : result will be as --- ravi kant soni
for (String name : list) {
...
}
//Now call this method
Collections.reverse(list);
// iterate and print index wise : result will be as --- soni kant ravi
for (String name : list) {
...
}
I am a newbie, I have a question.
I have a map. I have to loop through the map and build the iterator.
Example:
public Iterable<Test> getTests(Map<String, Test> testMap,
Set<String> strings)
{
//loop tru the set of strings and build iterator.
for(final String test1 : strings)
{
Test test = testMap.get(test1);
//build a iterator. not a list.
}
return iterator
}
How can I do this?
First of all, your method is returning an Iterable, not an Iterator. Map, Set, and List all implement Iterable, so it might be easier than you think.
Second, an Iterable is merely a class that has an iterator() method which returns an Iterator.
So I would simply build a List of the results and then return it. If you really want to return an Iterator, I would instead call iterator() on the list and return that.
Skipping over your Iterator/Iterable confusion (and Iterable is basically an Iterator factory... so you need to write an Iterator either way), I think you mean something like this:
Iterator<Test> getTests(final Map<String,Test> testMap, final Set<String> strings) {
return new Iterator<Test>() {
private final Iterator<String> keyIter = strings.iterator();
private String lastKey;
public boolean hasNext() { return keyIter.hasNext(); }
public Test next() { lastKey = keyIter.next(); return testMap.get(lastKey); }
public void remove() { testMap.remove(lastKey); }
};
}
And if you want to return an Iterable, well, that just has to be a factory for those:
Iterable<Test> getTests(final Map<String,Test> testMap, final Set<String> strings) {
return new Iterable<Test>() {
public Iterator<Test> iterator() {
return new Iterator<Test>() {
private final Iterator<String> keyIter = strings.iterator();
private String lastKey;
public boolean hasNext() { return keyIter.hasNext(); }
public Test next() { lastKey = keyIter.next(); return testMap.get(lastKey); }
public void remove() { testMap.remove(lastKey); }
};
}
};
}
For extra credit, you can parameterise this method itself and have a generic way of iterating over a selection from a map:
Map<String, Action> map;
Set<String> keys;
for (Action x : filterMap(map, keys)) {
}
Since Collection extends Iterable, the correct solution would be to add the tests to some sort of collection, like an ArrayList.
Collection<Test> tests = new ArrayList<Test>();
for (String key : strings) {
Test t = testMap.get(key);
if (t != null)
tests.add(t);
}
return tests;
If you want to really return Iterable simplest way is this
public Iterable<Test> getTests(Map<String, Test> testMap, Set<String> strings)
{
testMap = new HashMap<String, Test>(testMap);
testMap.keySet().retainAll(strings);
return testMap.values();
}
If you want to return an iterator, replace the last line with
return testMap.values().iterator();
If you don't care about modifications to the passed in map, skip the initial temp map construction.
EDIT:
removed use of clone on the Map interface which doesn't have it.
As a stab in the dark, what you may be looking for is Map.entrySet.iterator(). It allows you to iterate over the entries of the map.
Note: I know this is not an answer to the OP's question, but it's my guess at answering what they are actually looking for. If this guess turns out to be wrong, I'll delete this answer again to spare people the confusion.
An Iterable is something different from an Iterator. An Iterable is something you can iterate through, like a List. You use an Iterator for that. Your questions is not clear about what you want to return from getTests().
Your best shot would be to create an Iterable (like a List or Vector) and return that, or return its Iterator.