需要过滤2个列表和;添加到java中的单独列表中

时间:2014-04-09 08:11:31

标签: java list arraylist

我有2个名单:

  • avaliableRoomType - [Standard,SuperDeluxe]
  • wholeRoomtype - [Standard,SuperDeluxe,Deluxe]

我需要过滤这个&添加到单独的列表unavailableRoomtype - [Deluxe]

for(int j = 0; j <  avaliableRoomType.size()  ; j++) {

        for(int i = 0; i < wholeRoomtype.size(); i++) {

            String tempAv = avaliableRoomType.get(j);
            String tempHotelRoomId = wholeRoomtype.get(i);

            if(!tempAv.equals(tempHotelRoomId)){


            unavailableRoomtype.add(tempHotelRoomId);


            }

        }

    }

但我有重复的值。

4 个答案:

答案 0 :(得分:2)

List<String> unavailableRoomtype = new ArrayList<>();

for (String roomType : wholeRoomtype) {
  if (!avaliableRoomType.contains(roomType)) {
    unavailableRoomtype.add(roomType);
  }
}

答案 1 :(得分:1)

我建议使用Set代替List s:

Set<String>   roomTypes;        
Set<RoomType> availableRoomType;
Set<RoomType> unavailableRoomType;



示例实施

public static void main(String[] args) {
    final Set<String> roomTypes           = new LinkedHashSet<>();
    final Set<String> availableRoomType   = new LinkedHashSet<>();
    final Set<String> unavailableRoomType = new LinkedHashSet<>();

    roomTypes.add("Standard");
    roomTypes.add("Deluxe");
    roomTypes.add("SuperDeluxe");
    // .. other entries

    // determine what room types are available
    availableRoomType.add("Standard");
    availableRoomType.add("SuperDeluxe");


    // your filtering for unavailable room types
    roomTypes.stream()
            .filter(e -> !availableRoomType.contains(e))
            .forEach(unavailableRoomType::add);


    System.out.printf("Available room types:\n");
    availableRoomType.forEach(System.out::println);

    System.out.printf("\nUnavailable room types:\n");
    unavailableRoomType.forEach(System.out::println);
}

输出

  

可用房型:
  标准
  SuperDeluxe
      
  不可用的房型:
  豪华

答案 2 :(得分:0)

如果您不想要重复,请构建新的Set,然后将其转换回List

List<String> list = new ArrayList<>(set);

答案 3 :(得分:0)

for(String type : wholeRoomtype){
    if(!availableroomtype.contains(type) || !unavailableRoomtype.contains(type){
         unavailableRoomtype.add(type);
    }
}

在这里检查此类型是否已添加到unavailableRoomtype列表中。如果已添加,则不执行任何操作。