Removing an element from 3 common elements in android - java

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);

Related

Looping through different arrays lists

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));
}
}
}
}

Java List looping based of available size

I want to display only 12 sorted elements from myList. If the size is less than 12, say 5, or 3, or 1, still I need to loop and display only those available items.
Below is my code:
public class JavaApplication {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("20150830");
myList.add("20141201");
myList.add("20150716");
myList.add("20151131");
myList.add("20141101");
myList.add("20150620");
myList.add("20150301");
myList.add("20150702");
myList.add("20150511");
Collections.sort(myList,Collections.reverseOrder());
for(int i = 0; i < myList.size(); i++) {
System.out.println(myList.get(i).toString());
}
}
}
This is a good use-case for streams.
myList.stream()
.sorted(Comparator.<String>reverseOrder())
.limit(12)
.forEach(System.out::println);
Just add one more condition in your loop to restrict the loop for 12.
for(int i = 0; i < myList.size() && i < 12 ; i++){
System.out.println(myList.get(i).toString());
}
You can try:
int maxValuesToDisplay=12;
int maxToIterate=(myList.size()<maxValuesToDisplay) ? myList.size() : maxValuesToDisplay;
for(int i = 0; i < maxToIterate; i++){
System.out.println(myList.get(i).toString());
}
Use List.subList(int fromIndex, int toIndex);
public class JavaApplication {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("20150830");
myList.add("20141201");
myList.add("20150716");
myList.add("20151131");
myList.add("20141101");
myList.add("20150620");
myList.add("20150301");
myList.add("20150702");
myList.add("20150511");
Collections.sort(myList,Collections.reverseOrder());
int a = myList.size();
List subList = null;
if(a<12)
subList = myList.subList(0,a);
else subList = myList.subList(0,12);
//Print sublist now
}
}
You could use the Math.min() function and iterate the minimum of 12 and the list-size.
for(int i = 0; i < Math.min(myList.size(), 12); i++){
System.out.println(myList.get(i).toString());
}
You can use TreeSet :
public static void main(String[] args) {
Set<String> myList = new TreeSet<>();
myList.add("20150830");
myList.add("20141201");
myList.add("20150716");
myList.add("20151131");
myList.add("20141101");
myList.add("20150620");
myList.add("20150301");
myList.add("20150702");
myList.add("20150511");
int i = 0;
for(String s : myList){
System.out.println(s);
i++;
if(i >= 5) {
break;
}
}
}
And for reverse order :
public static void main(String[] args) {
TreeSet<String> myList = new TreeSet<>();
myList.add("20150830");
myList.add("20141201");
myList.add("20150716");
myList.add("20151131");
myList.add("20141101");
myList.add("20150620");
myList.add("20150301");
myList.add("20150702");
myList.add("20150511");
Iterator<String> it = myList.descendingIterator();
int i = 0;
while(it.hasNext()) {
String s = it.next();
System.out.println(s);
i++;
if (i >= 5) {
break;
}
}
}

Split ArrayList in multiple ArrayLists where values are same

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.

Comparting two ArrayList<String> lists in Java

Okay... So what I've been trying to do is compare two lists: words and d. The words they have in common need to be added to a third list: realWords.
Dictionary is just a list in a different class that has a bunch of words in it.
List<String> realWords = new ArrayList<String>();
Dictionary d = new Dictionary();
These are the things I've tried and haven't worked (and by "worked" I mean the output is nothing, no errors):
Attempt 1
List<String> realWords = new ArrayList<String>(words);
realWords.retainAll(d);
Attempt 2
for(int i = 0; i < words.size(); i++) {
if (d.contains(words.get(i))){
realWords.add(words.get(i));
}
}
Attempt 3
for(String word : words) {
if (d.contains(word)) {
realWords.add(word);
}
}
Attempt 4
for (int i = 0; i < words.size(); i++) {
for (int j = 0; i < d.size(); i++) {
if(words.get(i) == d.get(j)) {
realWords.add(words.get(i));
}
}
}
And then after that portion of code I'm missing:
return realWords;
Thanks in advance!
Edit1: The code for Dictionary.java is:
package a1;
import java.util.*;
public class Dictionary extends ArrayList<String> {
public Dictionary() {
this.add("abalone");
this.add("abandon");
this.add("abashed");
this.add("abashes");
this.add("abasing");
this.add("abating");
this.add("abdomen");
this.add("abducts");
this.add("abetted");
this.add("abetter");
this.add("abettor");
this.add("abiding");
this.add("ability");
this.add("abjured");
this.add("abjures");
this.add("abolish");
this.add("aborted");
this.add("abounds");
this.add("abraded");
// and then more words
}
}
NOTE: This code was provided to us and cannot be changed.
The following code has the following output: [abalone, abolish]
The problem must be somewhere else. Are you sure that "words" contains valid words? Try outputting it and checking manually.
public class Example {
public static class Dictionary extends ArrayList<String> {
public Dictionary() {
this.add("abalone");
this.add("abandon");
this.add("abashed");
this.add("abashes");
this.add("abasing");
this.add("abating");
this.add("abdomen");
this.add("abducts");
this.add("abetted");
this.add("abetter");
this.add("abettor");
this.add("abiding");
this.add("ability");
this.add("abjured");
this.add("abjures");
this.add("abolish");
this.add("aborted");
this.add("abounds");
this.add("abraded");
// and then more words
}
}
public static void main(String[] args) {
List<String> realWords = new ArrayList<String>(
Arrays.asList("abalone", "foobar", "abolish"));
Dictionary d = new Dictionary();
realWords.retainAll(d);
System.out.println(realWords);
}
}
EDIT: Your other attempts are functionally identical, they have the same complexity (O(words.size() * d.size()) but are longer and less obvious/clear.
The code works fine, please debug your code. See the output for reference.
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
words.add("abashes");
words.add("sdqad");
words.add("abducts");
words.add("sadadads");
List<String> realWords = new ArrayList<String>();
Dictionary d = new Dictionary();
for (int i = 0 ; i < words.size() ; i++) {
if (d.contains(words.get(i))) {
realWords.add(words.get(i));
}
}
System.out.println(realWords);
}
output
[abashes, abducts]
Using Java 8 streams I would suggest:
List<Strings> realWords = words.stream()
.filter(d::contains).collect(Collectors.toList());
You can use an enhance for loop
List<String> realWords = new ArrayList<>();
Dictionary d = new Dictionary();
List<String> words = new ArrayList<String>();
words.add("abetted");
words.add("ability");
for (String word : words) {
if (d.contains(word)) {
realWords.add(word);
}
}
System.out.println(realWords);
}
}

How to search for a string in an arraylist

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;
}
}
}
}

Categories

Resources