I want to search for a string in an arraylist.
My ArrayList contains:
ArrayList <String> list = new ArrayList();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
Now I want to search for "bea" and it should return a list containing "bear" and "beat".
How can I implement it?
List <String> list = new ArrayList();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List <String> listClone = new ArrayList<String>();
for (String string : list) {
if(string.matches("(?i)(bea).*")){
listClone.add(string);
}
}
System.out.println(listClone);
Loop through your list and do a contains or startswith.
ArrayList<String> resList = new ArrayList<String>();
String searchString = "bea";
for (String curVal : list){
if (curVal.contains(searchString)){
resList.add(curVal);
}
}
You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.
Nowadays, Java 8 allows for a one-line functional solution that is cleaner, faster, and a whole lot simpler than the accepted solution:
List<String> list = new ArrayList<>();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List<String> matches = list.stream().filter(it -> it.contains("bea")).collect(Collectors.toList());
System.out.println(matches); // [bear, beat]
And even easier in Kotlin:
val matches = list.filter { it.contains("bea") }
May be easier using a java.util.HashSet. For example:
List <String> list = new ArrayList<String>();
list.add("behold");
list.add("bend");
list.add("bet");
//Load the list into a hashSet
Set<String> set = new HashSet<String>(list);
if (set.contains("bend"))
{
System.out.println("String found!");
}
Since your list doesn't appear to be sorted, you have to iterate over its elements. Apply startsWith() or contains() to each element, and store matches in an auxiliary list. Return the auxiliary list when done.
Better way is to use matches() method on every String element of the array. This will help you to search any pattern through regular expressions.
The Best Order I've seen :
// SearchList is your List
// TEXT is your Search Text
// SubList is your result
ArrayList<String> TempList = new ArrayList<String>(
(SearchList));
int temp = 0;
int num = 0;
ArrayList<String> SubList = new ArrayList<String>();
while (temp > -1) {
temp = TempList.indexOf(new Object() {
#Override
public boolean equals(Object obj) {
return obj.toString().startsWith(TEXT);
}
});
if (temp > -1) {
SubList.add(SearchList.get(temp + num++));
TempList.remove(temp);
}
}
First you have to copy, from AdapterArrayList to tempsearchnewArrayList ( Add ListView items into tempsearchnewArrayList ) , because then only you can compare whether search text is appears in Arraylist or not.
After creating temporary arraylist, add below code.
searchEditTextBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String txt = charSequence.toString().trim();
int txtlength = txt.length();
if (txtlength > 0) {
AdapterArrayList = new ArrayList<HashMap<String, String>>();
for (int j = 0; j< tempsearchnewArrayList.size(); j++) {
if (tempsearchnewArrayList.get(j).get("type").toLowerCase().contains(txt)) {
AdapterArrayList.add(tempsearchnewArrayList.get(j));
}
}
} else {
AdapterArrayList = new ArrayList<HashMap<String, String>>();
AdapterArrayList.addAll(tempsearchnewArrayList);
}
adapter1.notifyDataSetChanged();
if (AdapterArrayList.size() > 0) {
mainactivitylistview.setAdapter(adapter1);
} else {
mainactivitylistview.setAdapter(null);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
List <String> list = new ArrayList();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List <String> listClone = new ArrayList<String>();
Pattern pattern = Pattern.compile("bea",Pattern.CASE_INSENSITIVE); //incase u r not concerned about upper/lower case
for (String string : list) {
if(pattern.matcher(string).find()) {
listClone.add(string);
continue;
}
}
System.out.println(listClone);
TRY using Google guava library
FOR MORE INFO --> https://github.com/google/guava
Iterable<String> result = Iterables.filter(yourListContainStringsYouWantToSearch, Predicates.containsPattern(search));
Log.i("resultsInList", "performSearch:\n"+ Lists.newArrayList(result.iterator()));
import java.util.*;
class ArrayLst
{
public static void main(String args[])
{
ArrayList<String> ar = new ArrayList<String>();
ar.add("pulak");
ar.add("sangeeta");
ar.add("sumit");
System.out.println("Enter the name:");
Scanner scan=new Scanner(System.in);
String st=scan.nextLine();
for(String lst: ar)
{
if(st.contains(lst))
{
System.out.println(st+"is here!");
break;
}
else
{
System.out.println("OOps search can't find!");
break;
}
}
}
}
Related
Removing common value from an ArrayList.
consider i have one Arraylist as shown below
arrayList1= [U1,U2,U3,.GY,.GY,.GY,U4,.GY,U5,U6,.GY,.GY,.GY]
My result should be
arrayList1= [U1,U2,U3,.GY,.GY,U4,.GY,U5,U6,.GY,.GY]
Could anyone please help me out.
Thanks in Advance
You can try something like this:
public static void main(String[] args) {
List<String> list = Arrays.asList("U1","U2","U3",".GY",".GY",".GY","U4",".GY","U5","U6",".GY",".GY",".GY");
System.out.println(removeCommon(list)); // [U1, U2, U3, .GY, .GY, U4, .GY, U5, U6, .GY, .GY]
}
static List<String> removeCommon(List<String> list) {
List<String> result = new ArrayList<>(list);
for (int i = 0; i < list.size() - 2; i++) {
if (list.get(i).equals(list.get(i + 1)) && list.get(i).equals(list.get(i + 2))) {
result.remove(i);
}
}
return result;
}
You can do that as following:
// arrayList1 is List of Strings
Set<String> s = new LinkedHashSet<>(arrayList1);
I have three different arrays of different sizes to gather node status and I would like to iterate through all of them with one loop instead of creating one for each. I've seen examples with naming the array as an integer and doing a while/for loop and incrementing, but I would like to find a method to keep the current array names. Here is what I have so far.
EDIT : I would like to keep all lists separate so that it is easily distinguishable what nodes have what status.. i.e.
Online - node1, node2 | Offline - node3, node4 | Unknown - node5, node6
private String nodeStatus() {
List<Node> onlineNodes = new ArrayList<Node>();
List<Node> offlineNodes = new ArrayList<Node>();
List<Node> unknownNodes = new ArrayList<Node>();
for(Node n : getNodes()){
if (n.isRunning() == RunningType.ONLINE) {
onlineNodes.add(n);
}
if (n.isRunning() == RunningType.OFFLINE) {
offlineNodes.add(n);
}
if (n.isRunning() == RunningType.UNKNOWN) {
unknownNodes.add(n);
}
}
for (Node element : <online,offline,unknown>) {
System.out.println(element);
}
}
If I understand correctly, what you want is to iterate through 3 lists on 1 for-loop w/o using a 4th list, the way you can achieve this is:
import java.util.*;
public class MultipleArraysLooping {
public static void main (String args[]) {
List <String> list1 = new ArrayList <String>();
List <String> list2 = new ArrayList <String>();
List <String> list3 = new ArrayList <String>();
fillLists(list1, list2, list3);
iterateLists(list1, list2, list3);
}
public static void fillLists(List <String> list1,
List <String> list2, List <String> list3) {
list1.add("item1 on list1");
list1.add("item2 on list1");
list1.add("item3 on list1");
list2.add("item1 on list2");
list2.add("item2 on list2");
list2.add("item3 on list2");
list2.add("item4 on list2");
list2.add("item5 on list2");
list3.add("item1 on list3");
list3.add("item2 on list3");
}
public static void iterateLists(List <String> list1,
List <String> list2, List <String> list3) {
int size = 0;
if (list1.size() > list2.size()) {
if (list1.size() > list3.size()) {
size = list1.size();
} else {
size = list3.size();
}
} else {
if (list2.size() > list3.size()) {
size = list2.size();
} else {
size = list3.size();
}
}
for (int i = 0; i < size; i++) {
if (i < list1.size()) {
System.out.println(list1.get(i));
}
if (i < list2.size()) {
System.out.println(list2.get(i));
}
if (i < list3.size()) {
System.out.println(list3.get(i));
}
}
}
}
The output given by the above code is:
item1 on list1
item1 on list2
item1 on list3
item2 on list1
item2 on list2
item2 on list3
item3 on list1
item3 on list2
item4 on list2
item5 on list2
As you can see, it iterates over each list alternatively
I hope this helps, probably there's a better way to get the largest size of the arrays.
If what you want is to iterate the 3 of them in order (list 1 complete, then list 2 and lastly list 3) or by some state, well, you need to add your logic there
You might want to keep a map of statuses to elements instead of having 3 separate variables. Assuming you have Java 8 and getNodes() returns a Collection, you can do something like this:
Map<String, List<Node>> elementsByStatus = getNodes().stream()
.collect(Collectors.groupingBy(Node::isRunning));
// print all elements
elementsByStatus.stream()
.flatMap(List::stream)
.forEach(System.out::println);
If you need to iterate over elements by status, you can do this:
elementsByStatus.forEach((status, elements) -> {
elements.forEach(element -> {
//...
});
});
You Can try by this:
public class ListIterator {
public static void print(List<String> list){
for (String string : list) {
System.out.println(string);
}
}
public static void main(String[] args) {
List<String> list1=new ArrayList<>();
List<String> list2=new ArrayList<>();
List<String> list3=new ArrayList<>();
list1.add("List11");
list1.add("List12");
list1.add("List14");
print(list1);
System.out.println();
list2.add("List21");
list2.add("List22");
print(list2);
System.out.println();
list3.add("List3");
print(list3);
System.out.println();
}
}
You can also try this:
public class ListIterator {
public static void print(List<String> list){
for (String string : list) {
System.out.println(string);
}
}
public static void main(String[] args) {
List<String> list1=new ArrayList<>();
List<String> list2=new ArrayList<>();
List<String> list3=new ArrayList<>();
list1.add("List11");
list1.add("List12");
list1.add("List13");
list2.add("B1");
list2.add("B2");
list3.add("C1");
int a=list1.size();
int b=list2.size();
int c=list3.size();
int max=Math.max(a, b);
max=Math.max(max, c);
//System.out.println("");
for(int i=0;i<max;i++){
if (i<list1.size()) {
System.out.println(list1.get(i));
}
if (i<list2.size()) {
System.out.println(list2.get(i));
}
if (i<list3.size()) {
System.out.println(list3.get(i));
}
}
}
}
Well im stuck on this point.
im trying to make sort function what does this.
parentarraylist = [1,1,1,2,3,2,3,3,2,2,1];
*magic*
childarraylist1 = [1,1,1,1];
childarraylist2 = [2,2,2,2];
childarraylist3 = [3,3,3];
the magic part is where im stuck.
i have tryied putting it in an for loop(the parent) and checking on the value. like this
int i = 0;
int finder = 0;
ArrayList<int> initArray = new ArrayList();
for(int list : parentarraylist){
if(i == 0){
finder = list
}
if(finder == list){
initArray.add(list);
parentarraylist.remove(list);
}else{
new ArrayList *value of list* = new ArrayList();
finder = list;
*value of list*.add(list);
}
}
this results in a view errors like
java.util.ConcurrentModificationException
and i cant set value of list
what can i do to make this work?
This little snippet should help you achieve your goal:
//maps will hold ALL unique integer as it's key
HashMap<Integer, ArrayList<Integer>> maps = new HashMap<Integer, ArrayList<Integer>>();
//your initial array, written inline for clarity
ArrayList<Integer> parentarraylist = new ArrayList<Integer>(Arrays.asList( new Integer[] {1,1,1,2,3,2,3,3,2,2,1}));
//get the iterator so that we won't need another temporary int variable for loop
Iterator<Integer> iterator = parentarraylist.iterator();
while(iterator.hasNext()){
//next = current integer in our array
Integer next = iterator.next();
//check if we have already have current integer or not
if(!maps.containsKey(next)){
//we don't have it, initialise an arraylist for this specific integer
ArrayList<Integer> x = new ArrayList<Integer>();
x.add(next);
//put it to our map holder
maps.put(next, x);
} else {
//already have it, add directly
maps.get(next).add(next);
}
}
This codes will print something like this:
printMap(maps);
//1 = [1, 1, 1, 1]
//2 = [2, 2, 2, 2]
//3 = [3, 3, 3]
printMap() is taken from this answer: Iterate through a HashMap
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
You could try something like this:
public static void main(String[] args) {
ArrayList<Integer> parent = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
parent.add(3);
parent.add(1);
parent.add(1);
parent.add(2);
parent.add(3);
parent.add(3);
parent.add(1);
for(int i : parent)
{
boolean check = false;
for(ArrayList<Integer> result : results)
{
if(result.size() > 0)
{
if(result.get(0) == i)
{
check = true;
result.add(i);
break;
}
}
}
if(!check)
{
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(i);
results.add(temp);
}
}
for(ArrayList<Integer> i : results)
{
for(int j : i)
{
System.out.print("" + j);
}
System.out.println();
}
}
Output:
333
111
2
The problem is that you remove an element from an array over which you are iterating. The
parentArrayList.remove(list);
causes the error here. If you remove this line your program will work. At the moment I do not see the benefit of removing the item from the parentArrayList for your sorting algorithm so just delete it and you are good to go.
With the help of the community i managed to get this problem solved: How to convert String to the name of the Array?
But now i get 'nullPointerExceptions'. Here is the code i use:
public class IroncladsAdder
{
public static String weaponId = null;
public static String ship = null;
public static String wing = null;
//map code
private static Map<String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public void Holder(String... names) {
for (String name : names) {
arrays.put(name, new ArrayList<Integer>());
}
}
//adds weapons to fleets and stations
public static void AddWeapons(CargoAPI cargo, String fac, int count, int type) {
String arrayName = null;
int quantity = (int) (Math.random()*5f + count/2) + 1;
if (count == 1) {quantity = 1;}
if (type == 0) {arrayName = fac+"_mil_weps";}
else if (type == 1) {arrayName = fac+"_civ_weps";}
else {arrayName = fac+"_tech_weps";}
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
cargo.addWeapons(weaponId, quantity);
}
}
Here is an example of the array:
//high-tech UIN weapons
private static String [] uin_tech_weps =
{
"med-en-uin-partpulse",
"lrg-en-uin-partacc",
"med-bal-uin-driver",
"lrg-bal-uin-terminator",
"lrg-bal-uin-hvydriver",
"lrg-bal-uin-shotgundriver",
"lrg-en-uin-empbeam",
};
Error indicates that something is wrong with this construction:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
NOTE: i`m using Intellij IDEA and Java 6. Application most of the time has advices/fixes for some errors and in this case shows that everything is ok.
What i need is to get a String out of the specific array (that is using a code-generated name) and assign it to 'weaponId'.
When your application start the map with the arrays is empty, then when you try to get the array with name X you get back a null value.
First solution: at startup/construction time fill the map with empty arrays/List for all the arrays names.
Second solution: use this method in order to obtain the array.
protected List<Integer> getArray(String arrayName) {
List<Integer> array = map.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
map.put(arrayName, array);
}
return array;
}
P.s.
You can change this code:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
into
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
Ok. Now there is a different error - 'java.lang.IndexOutOfBoundsException: Index: 0, Size: 0'
Made the code look like this:
private static Map <String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public static List<Integer> getArray(String arrayName) {
List<Integer> array = arrays.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
arrays.put("rsf_civ_weps", array);
arrays.put("rsf_mil_weps", array);
arrays.put("rsf_tech_weps", array);
arrays.put("isa_civ_weps", array);
arrays.put("isa_mil_weps", array);
arrays.put("isa_tech_weps", array);
arrays.put("uin_mil_weps", array);
arrays.put("uin_tech_weps", array);
arrays.put("uin_civ_weps", array);
arrays.put("xle_civ_weps", array);
arrays.put("xle_mil_weps", array);
arrays.put("xle_tech_weps", array);
}
return array;
}
This is how i now call the array and weaponId:
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
cargo.addWeapons(weaponId, quantity);
}
What`s wrong?
i have an arrayList ( named error_dub ) i want to print the duplicates only one time here is my code
for(x=0 ; x<=error_dub.size()-1 ; x++){
for(int h=x+0 ; h<=error_dub.size() ; h++){
if(error_dub.get(x).equals(error_dub.get(h) && x!=h){
System.out.println(error_dub.get(x)+" is duplicated ");
}
}
}
here the line is printed more than once so how can i printed only once ?
Use two sets (this assumes X is the class of your object):
// Returns a set of all duplicates in a list
public Set<X> getDuplicates(final List<X> list)
{
final Set<X> dups = new HashSet<X>();
final Set<X> set = new HashSet<X>();
/*
* Cycle through all elements in the original list. Add it to "set":
*
* - if the .add() method returns true, this is the first time the element is seen;
* - if it returns false, then this is not the first time, it is a duplicate:
* add it to "dups".
*/
for (final X element: list)
if (!set.add(element))
dups.add(element);
return dups;
}
Set's .add() will return false if the set is not modified as a result of the operation, which means if the element was already there.
Copy/paste that function into your existing code and replace the snippet above with:
for (final X dup: getDuplicates(error_dub))
System.out.println(dup + " is duplicated");
Important note: the getDuplicates() function as it is written will NOT respect element order. If order matters to you, replace dups with a LinkedHashSet instead of a HashSet.
you can use .add() method of set to check for duplicates. Method posted below adds list elements to set1. If element is a duplicate (.add() returns true), then element is adde to setToReturn
public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)
{
final Set<Integer> setToReturn = new HashSet();
final Set<Integer> set1 = new HashSet();
for (Integer yourInt : listContainingDuplicates)
{
if (!set1.add(yourInt))
{
setToReturn.add(yourInt);
}
}
return setToReturn;
}
ArrayList<String> ar=new ArrayList<String>();
ArrayList<String> ar2=new ArrayList<String>();
ar.add("1");
ar.add("2");
ar.add("3");
ar.add("4");
ar.add("5");
ar.add("1");
ar.add("2");
ar.add("1");
for(int x=0;x<ar.size();x++)
{
if(!ar2.contains(ar.get(x)))
{
for(int y=x+1;y<ar.size()-1;y++)
{
if((ar.get(y).equals(ar.get(x))))
{
System.out.print("repeating "+ar.get(x));
ar2.add(ar.get(x));
break;
}
}
}
}
you can do like this.
//method to identify the duplicate elements in array list
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
public class Dup
{
public static void main(String[] args)
{
ArrayList<Integer> a=new ArrayList<Integer>();
System.out.println("enter elements");
int g;
Scanner b= new Scanner(System.in);
for(int i=0;i<10;i++)
{
g=b.nextInt();
a.add(g);
}
HashSet<Integer> c=new HashSet<Integer>();
ArrayList<Integer> d=new ArrayList<Integer>();
for (Integer y : a)
{
if (c.contains(y))
{
d.add(y);
}
else
c.add(y);
}
System.out.println("original elements are:"+c);
System.out.println("duplicate elements are:");
for(Integer h:d)
{
System.out.println(h);
}
}
}