List and Map in java programing - list

I need to convert:
List<Map>([{1,2},{2,3}])
To:
List<List>([[1,2],[2,3]])
Can anyone help me with example for this ...
Thanks

I would suggest making a list of specific objects instead of a raw list that the get(0) returns the key and get(1) the value as follows:
List<List<Pair>> convert(List<Map<Integer,Integer> mapList){
List<List<Pair>> listOfList = new ArrayList<List<Pair>>();
for(Map<Integer,Integer> map:mapList){
List<Pair> list = new ArrayList<Pair>();
for(Entry<Integer,Integer> e:map.entrySet()){
list.add(Pair(e.getKey(),e.getValue());
}
listOfList.add(list);
}
return listOfList;
}
class Pair{
Integer first;
Integer second;
//constructor
}

You can try the following Code:
import java.util.*;
class ListOfMapToListOfList
{
public static List<List> toList(List<Map<Integer,Integer>> lList)//method to convert List<Map> to List<List>
{
List<List> list = new ArrayList<List>();
for (int i = 0 ; i < lList.size() ; i++)
{
Map<Integer,Integer> map = lList.get(i);
List<Integer> aList = new ArrayList<Integer>();
Set<Integer> keySet = map.keySet();
for (Integer key : keySet)
{
aList.add(key);
aList.add(map.get(key));
}
list.add(aList);
}
return list;
}
public static void main(String[] args) //main body
{
List<Map<Integer,Integer>> list1 = new ArrayList<Map<Integer,Integer>>();
Map<Integer,Integer> map1 = new HashMap<Integer,Integer>();
map1.put(1,2);
Map<Integer,Integer> map2 = new HashMap<Integer,Integer>();
map2.put(1,2);
list1.add(map1);list1.add(map2);
System.out.println(list1);
System.out.println(toList(list1));//Conversion is done here..and out put is shown.
}
}

Related

Dart print multiple list item at once

How can I type something like "print(list[1,4]);" in Dart?
For example:
int main() {
var products = new List(5);
products[0] = "Laptop";
products[1] = "Mouse";
products[2] = "Keyboard";
products[3] = "Monitor";
products[4] = "Microphone";
print(products[1]); // Mouse
print(products[1,3]); // I want to see 'Mouse,Monitor'
}
This is not directly supported in the SDK but you can easily make a extension on e.g. List to add this feature:
void main() {
final products = List<String>(5);
products[0] = "Laptop";
products[1] = "Mouse";
products[2] = "Keyboard";
products[3] = "Monitor";
products[4] = "Microphone";
print(products[1]); // Mouse
print(products.selectMultiple([1,3]).join(',')); // Mouse,Monitor
}
extension MultiSelectListExtension<E> on List<E> {
Iterable<E> selectMultiple(Iterable<int> indexes) sync* {
for (final index in indexes) {
yield this[index];
}
}
}
You can't make it so [1,3] (as in you own example) would be valid since the [] operator does only allow one argument. So instead, we need to make a method which takes our requested indexes as argument.

How to get the same attribute from all objects in a list in one line

I have a list of objects of the same class.
This class contains an attribute I want to use.
I would like to get a list of all these attributes in one line. Is this possible?
Here is a small example: I just want a list of all the colors.
It is important that I return directly a list of these attributes, without the normal forEach statement.
void main() {
List<Car> listOfCars = [
Car('blue'),
Car('green'),
Car('yellow'),
];
}
//List<String> listOfColors = listOfCars[all].color;
class Car{
String color;
Car(this.color);
}
You can use the map function to achieve this
List<String> listOfColors = listOfCars.map((car) => car.color).toList();
print(listOfColors);
Just check out this code below:
void main() {
List<Car> listOfCars = [
Car('blue'),
Car('green'),
Car('yellow'),
];
List<String> stringList = List();
// This is where you get the single car object and then you add it the list of string
for (int i = 0; i < listOfCars.length; i++) {
stringList.add(listOfCars[i].color);
}
// this is the desired out put i have just printed your list :
print('This is the string length : ' + stringList.length.toString());
for (int i = 0; i < stringList.length; i++) {
print('This is the string list :' + stringList[i]);
}
}
class Car {
final String color;
Car(this.color);
}
Blow is the output :
This is the string length : 3
This is the string list :blue
This is the string list :green
This is the string list :yellow

Display a chunked items list in Java 8

With the following code:
public class Main {
public static void main(String[] args) {
final List<Integer> items =
IntStream.rangeClosed(0, 23).boxed().collect(Collectors.toList());
final String s = items
.stream()
.map(Object::toString)
.collect(Collectors.joining(","))
.toString()
.concat(".");
System.out.println(s);
}
}
I get:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23.
What I would like to do, is to break the line every 10 items, in order to get:
0,1,2,3,4,5,6,7,8,9,
10,11,12,13,14,15,16,17,18,19,
20,21,22,23.
I have try a lot of things after googling without any success !
Can you help me ?
Thanks,
Olivier.
If you're open to using a third-party library, the following will work using Eclipse Collections Collectors2.chunk(int).
String s = IntStream.rangeClosed(0, 23)
.boxed()
.collect(Collectors2.chunk(10))
.collectWith(MutableList::makeString, ",")
.makeString("", ",\n", ".");
The result of Collectors2.chunk(10) will be a MutableList<MutableList<Integer>>. At this point I switch from the Streams APIs to using native Eclipse Collections APIs which are available directly on the collections. The method makeString is similar to Collectors.joining(). The method collectWith is like Stream.map() with the difference that a Function2 and an extra parameter are passed to the method. This allows a method reference to be used here instead of a lambda. The equivalent lambda would be list -> list.makeString(",").
If you use just Eclipse Collections APIs, this problem can be simplified as follows:
String s = Interval.zeroTo(23)
.chunk(10)
.collectWith(RichIterable::makeString, ",")
.makeString("", ",\n", ".");
Note: I am a committer for Eclipse Collections.
If all you want to do is process these ascending numbers, you can do it like
String s = IntStream.rangeClosed(0, 23).boxed()
.collect(Collectors.groupingBy(i -> i/10, LinkedHashMap::new,
Collectors.mapping(Object::toString, Collectors.joining(","))))
.values().stream()
.collect(Collectors.joining(",\n", "", "."));
This solution can be adapted to work on an arbitrary random access list as well, e.g.
List<Integer> items = IntStream.rangeClosed(0, 23).boxed().collect(Collectors.toList());
String s = IntStream.range(0, items.size()).boxed()
.collect(Collectors.groupingBy(i -> i/10, LinkedHashMap::new,
Collectors.mapping(ix -> items.get(ix).toString(), Collectors.joining(","))))
.values().stream()
.collect(Collectors.joining(",\n", "", "."));
However, there is no simple and elegant solution for arbitrary streams, a limitation which applies to all kind of tasks having a dependency to the element’s position.
Here is an adaptation of the already linked in the comments Collector:
private static Collector<String, ?, String> partitioning(int size) {
class Acc {
int count = 0;
List<List<String>> list = new ArrayList<>();
void add(String elem) {
int index = count++ / size;
if (index == list.size()) {
list.add(new ArrayList<>());
}
list.get(index).add(elem);
}
Acc merge(Acc right) {
List<String> lastLeftList = list.get(list.size() - 1);
List<String> firstRightList = right.list.get(0);
int lastLeftSize = lastLeftList.size();
int firstRightSize = firstRightList.size();
// they are both size, simply addAll will work
if (lastLeftSize + firstRightSize == 2 * size) {
System.out.println("Perfect!");
list.addAll(right.list);
return this;
}
// last and first from each chunk are merged "perfectly"
if (lastLeftSize + firstRightSize == size) {
System.out.println("Almost perfect");
int x = 0;
while (x < firstRightSize) {
lastLeftList.add(firstRightList.remove(x));
--firstRightSize;
}
right.list.remove(0);
list.addAll(right.list);
return this;
}
right.list.stream().flatMap(List::stream).forEach(this::add);
return this;
}
public String finisher() {
return list.stream().map(x -> x.stream().collect(Collectors.joining(",")))
.collect(Collectors.collectingAndThen(Collectors.joining(",\n"), x -> x + "."));
}
}
return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}
And usage would be:
String result = IntStream.rangeClosed(0, 24)
.mapToObj(String::valueOf)
.collect(partitioning(10));

Remove some elements stored in the list with the indexes present in other list

Q:Remove some elements stored in the list with the indexes present in other list? for eg.
List 1 has a, b, c, d, e and List 2 has 0,2 then a and c should be removed.
I have done a implementation of this ,not sure how efficent\in-efficent this is
public class RemoveByIndexFromOtherList {
public static void main(String[] args) {
List<String> lOriginal = new ArrayList<String>();
lOriginal.add("a");
lOriginal.add("b");
lOriginal.add("c");
lOriginal.add("d");
lOriginal.add("e");
List<Integer> indexes = new ArrayList<Integer>();
indexes.add(0);
indexes.add(2);
List<String> elemToRemove = new ArrayList<String>();
for (Integer index : indexes) {
String b = lOriginal.get(index.intValue());
elemToRemove.add(b);
}
for (String s : lOriginal) {
if (elemToRemove.contains(s)) {}
else {
System.out.println(s);
}
}
}
}
Kindly suggest, how this can be improved to a fair good efficient level
Not sure if you still need an answer/recommendation.
Instead of removing you can create a new list and add indexes not present in the second list. And then just change a reference. In Your case if you have multiple "a"s in a list, all of them will get removed.
Suggestion:
import java.util.ArrayList;
import java.util.List;
public class RemoveByIndexFromOtherList {
public static void main(String[] args) {
List<String> lOriginal = new ArrayList<String>();
lOriginal.add("a");
lOriginal.add("b");
lOriginal.add("c");
lOriginal.add("d");
lOriginal.add("e");
lOriginal.add("a");
List<Integer> indexes = new ArrayList<Integer>();
indexes.add(0);
indexes.add(2);
List<String> newListOriginal = new ArrayList<String>();
for(int i = 0; i<lOriginal.size(); i++){
if(!indexes.contains(i)){
newListOriginal.add(lOriginal.get(i));
}
}
lOriginal = newListOriginal;
for(String str: lOriginal){
System.out.println(str);
}
}
}

LWUIT List not scrolling

I have inserted a list in my j2ME project,designed using LWUIT. The code is as follows
Button btnHome;
Button btnExit;
List list;
setScrollableY(false);
setScrollable(false);
list = new List();
MyRenderer render = new MyRenderer();
list.setListCellRenderer(render);
list.getStyle().setFgColor(0xfaedf2);
list.setSmoothScrolling(true);
list.addSelectionListener(new SelectionListener(){
public void selectionChanged(int i, int i1) {
try {
InformationForm form = new InformationForm();
form.show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
String[] arrString = builder.getArrName();
System.out.println(arrString.length);
for (int i = 0; i < arrString.length ; i++)
{
list.addItem(arrString[i]);
// System.out.println("item no " + i +" = " +arrString[i] + "added in list");
}
BorderLayout bl=new BorderLayout();
setLayout(bl);
Container holdingContainer=new Container(new FlowLayout(Component.LEFT));
Container c0 = new Container(new BoxLayout(BoxLayout.X_AXIS));
Container c1 = new Container(new FlowLayout(Component.LEFT));
Container c2 = new Container(new FlowLayout(Component.LEFT));
Container footerContainer=new Container(new BoxLayout(BoxLayout.X_AXIS));
c0.addComponent(cityChoice);
c0.addComponent(btnFilter);
//c2.addComponent(list);
c1.setPreferredH(25);
holdingContainer.addComponent(c0);
holdingContainer.addComponent(c1);
getStyle().setBgColor(0x730E36);
// holdingContainer.addComponent(c2);
holdingContainer.setPreferredH(280);
holdingContainer.setScrollableY(true);
addComponent(BorderLayout.CENTER,list);
//addComponent(BorderLayout.WEST,holdingContainer);
footerContainer.getStyle().setMargin(Component.LEFT, 0);
footerContainer.addComponent(btnHome);
footerContainer.addComponent(btnExit);
addComponent(BorderLayout.SOUTH,footerContainer);
The renderer for list is,
public class MyRenderer extends TextArea implements ListCellRenderer{
public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected){
getStyle().setBorder(Border.createEmpty());
getStyle().setFgColor(0xfaedf2);
getStyle().setBgColor(isSelected ? 0x630A2E : 0x730E36);
setText(value.toString());
if (isSelected) {
setFocus(true);
getStyle().setBgTransparency(100);
} else {
setFocus(false);
getStyle().setBgTransparency(0);
}
return this;
}
public Component getListFocusComponent(List list){
return null;}
}
The problem is when on device, i try to scroll the list, the item on which i touched is selected immediatly and the new form for it is opened. I do not able to scroll the list at all. Please help me in solving this problem.
Is it possible you are using a SelectionListener instead of an ActionListener?