I've had an array of enums like below:
enum CountryEnum {
MADAGASCAR,
LESOTHO,
BAHAMAS,
TURKEY,
UAE
}
List<CountryEnum> countryList = new ArrayList<>();
countryList.add(CountryEnum.MADAGASCAR);
countryList.add(CountryEnum.BAHAMAS);
How to convert my countryList into String[]?
I've tried this way:
String[] countries = countryList.toArray(String::new);
but it returned me ArrayStoreException.
It should work so:
String[] strings = countryList.stream() // create Stream of enums from your list
.map(Enum::toString) // map each enum to desired string (here we take simple toString() for each enum)
.toArray(String[]::new); // collect it into string array
you can try this:
enum CountryEnum {
MADAGASCAR("Madagascar"),
LESOTHO("Lesotho"),
BAHAMAS("Bahamas"),
TURKEY("Turkey"),
UAE("UAE");
String country;
CountryEnum(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
}
I added a constructor to be able to get (in String) enum's values. Now you can just use:
List<String> countryList = new ArrayList<>();
countryList.add(CountryEnum.MADAGASCAR.getCountry());
countryList.add(CountryEnum.BAHAMAS.getCountry());
👍 😀
Related
I have two ArrayLists
private ArrayList<ArrayList<String> dataList = new ArrayList<>();
//This is a class variable
ArrayList<String> dataRow = new ArrayList<>();
//This is a method variable
I add items to dataRow
dataRow.add("number");
dataRow.add("firstName");
dataRow.add("surname");
dataRow.add("dateStart");
dataRow.add("dateEnd");
and then I add each dataRow to dataList resulting in an ArrayList of ArrayLists
dataList.add(dataRow);
My Question is:
I need to select just elements 3 and 4 from each dataRow and I can't find any code that works.
I have tried
for (ArrayList<String> eachRow : dataList)
{
For (String eachElement : eachRow)
(
System.out.println(eachElement)
}
}
All this does is print out all the elements
I have also tried other code such as
dataList.get(eachElement)
this throws a no suitable method error in netbeans
I worked it out as soon as I had posted this.
The code in the inner for loop should be:
System.out.println(eachRow.get(4));
Assuming you want to extract only two array elements, you could use a simple POJO for that:
class YourPojo { // rename it to something self-explanatory
private String field3;
private String field4;
// getters & setters
}
Then define an utility method extracting the data into your POJO from the raw array:
static YourPojo extractYourPojo(List<String> rawData){
YourPojo pojo = new YourPojo();
pojo.setField3(rawData.get(3));
pojo.setField4(rawData.get(4));
return pojo;
}
Then you can use the method as follows:
List<YourPojo> extracted =
dataList.stream()
.map(ClassWithUtilityMethod::extractYourPojo)
.collect(toList());
You can have a class to store values like below,
class ExtractedValue {
private String value3;
private String value4;
public ExtractedValue(String value3, String value4) {
this.value3 = value3;
this.value4 = value4;
}
public String getValue3() {
return value3;
}
public String getValue4() {
return value4;
}
}
And use the below to extract the 3rd and 4th values,
List<ExtractedValue> extracted= dataList.stream().map(l -> new ExtractedValue(l.get(3), l.get(4)))
.collect(Collectors.toList());
To print you can use the below,
extracted.stream().forEach(e -> {
System.out.println(e.getValue3());
System.out.println(e.getValue4());
});
I have a Java list of objects which each one contains a String value (code). Also I have a Java Map. I want to check whether all the elements in the Map keys are included in the list of the String values.
The Model class :
public class Obj {
private String code;
private String name;
private String uom;
public Obj(String code, String name, String uom) {
this.code = code;
this.name = name;
this.uom = uom;
}
}
the implemention :
private static final Obj weight = new Obj("weight", "Weight", "Kg");
private static final Obj height = new Obj("height", "Height", "cm");
public static final List<Obj> objMasters = List.of(weight, height);
Set<String> keySet = map.keySet(); // returns the keyset values from the Map
boolean match =objMasters.stream()
.anyMatch(objMaster -> objMaster.getCode().matches(keySet.toString()));
But with this implementation I always get false as the value for the match. What has gone wrong here?
From what I now understood about your question, try this.
List<String> codes = objMasters.stream().map(obj -> obj.getCode()).collect(Collectors.toList());
boolean match = codes.containsAll(keySet);
0,when you use collection or map,please override equals and hashCode methods
/n1,you can deep study of source code like get() contain() and others methods
/n2, by then you will undunderstand why
Is there a shorter way to create sublist from other list?
For example:
I have a Contact obiect, this obiect contain String field of adres
public List<String> getAdreses(long personID) {
List<String> adreses=null;
for(Contact mail : getContacts(personID)){
adreses.add(mail.getMail());
}
return adreses;
}
Try Java Stream:
List<String> adreses = getContacts(personID).stream().map(Contact::getMail).collect(Collectors.toList())
I checked many examples but i could not applied for my variables.
I have a ArratyList Of lists of Strings.
ArrayList<List<String>> bulkUploadList = new ArrayList<List<String>>();
and it's look like this:
[id, title, tags, descriptions]
[4291483113.0000000000000, Camden, camdentown;london, NoValue]
[4292220054.0000000000000, IMG_2720, NoValue, NoValue]
[4292223824.0000000000000, IMG_2917, london;camdentown, NoValue]
[4292224728.0000000000000, IMG_2945, London;CamdenTown, NoValue]
I want to remove those rows which have the same titles and the same tags.
I do not know how work with HashSet since I have a ArrayList of List of Strings.
Not best solution, but you can start with this:
ArrayList<List<String>> bulkUploadList = new ArrayList<List<String>>();
ArrayList<List<String>> result = new ArrayList<List<String>>();
HashSet<String> hashSet = new HashSet<>();
for(List<String> item : bulkUploadList) {
String title = item.get(1);
String tags = item.get(2);
String uniqueString = (title + "#" + tags).trim().toUpperCase();
if(!hashSet.contains(uniqueString)) {
result.add(item);
hashSet.add(uniqueString);
} else {
System.out.println("Filtered element " + uniqueString);
}
}
As suggested in one of the comments, you should create a class for the data, make that class implement equals(), and then use HashSet to remove dups. Like this.
class Foo {
String id;
String title;
String tags;
String description;
public boolean equals(Foo this, Foo other) {
return this.id.equals(other.id)
&& this.title.equals(other.title)
&& etc.
}
then you can remove dups with
Set<Foo> set = new LinkedHashSet<Foo>(list);
as Sets do not allow duplication, and the equals() method is used to check.
You should use a linkedHashSet here because you want to preserve the order (according to a comment you made on elsewhere).
You should also implement a hashcode() method consistent with equals().
I converted the ArrayList<String> list which contains "String1", "String2" to String by using list.toString(). The resulted string format is [String1, String2]. Is there any way to convert this result back to ArrayList<String>?
Try applying the following code
String value = "[String1,String2,String3]";
value = value.subString(1,value.length()-1);
String[] split = value.split(",");
List<String> sampleList = Arrays.asList(split);
create a new Class extending Array List
public class CustomArrayList<Item> extends ArrayList<Item> {
and override
toString
method, which could give a comma separated String representation.
Now use
new CustomArrayList<Item>(Arrays.asList(list.toString().split(",")))
to get it back in ArrayList.
No direct way. Just get that String remove those [] from String and then split by , then add back to list.
Something like this,considering the given format.
String s = "[String1, String2]";
s = s.substring(1, s.length() - 1);
List<String> list = new ArrayList<>();
for (String string : s.split(",")) {
list.add(string.trim());
}